vue+springboot实现图片的上传及回显失败问题的解决

    科技2023-10-04  76

    vue+springboot实现图片的上传及回显失败问题的解决

    <div class="upload"> <input type="file" id="saveImage" accept="image/png,image/gif,image/jpeg" ref="new_image"> <input type="text" hidden id="hiddenContent" v-model="picAddress"> <input type="button" value="上传头像" @click="submitPhoto()"/> <div class="photo"> <img :src="url" class="img" > </div> </div>

    submitPhoto():

    submitPhoto() { let self = this; if (self.$refs.new_image.files.length !== 0) { let formData = new FormData(); formData.append('image_data', self.$refs.new_image.files[0]); this.$axios.post('api/user/uploadPhoto', formData) .then(res => { let imgUrl = res.data; this.uploadPhotot(imgUrl); }) } },

    这里的imgUrl就是图片的路径,可以在浏览器中直接访问得到的。 uploadPhoto就是把图片路径及其他数据存到数据库的方法。 springboot中这样写:

    @PostMapping("/uploadPhoto") @ApiOperation(value = "上传头像", notes = "上传头像") public String uploadPhoto(@RequestParam(name = "image_data", required = false) MultipartFile file) throws IOException { // 文件上传 String imageName = file.getOriginalFilename(); String newCompanyImagePath = ""; if (!file.isEmpty()) { try { //D:\\Program Files (x86)\\workspace-spring-tool-suite-4-4.6.2.RELEASE\\csi\\src\\main\\resources\\static\\img\\ newCompanyImagePath = "D:\\Program Files (x86)\\workspace-spring-tool-suite-4-4.6.2.RELEASE\\csi\\src\\main\\resources\\static\\img\\" + imageName; File newFile = new File(newCompanyImagePath); if (!newFile.exists()) { newFile.createNewFile(); } BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(newFile)); out.write(file.getBytes()); out.flush(); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); return "图片上传失败!"; } catch (IOException e) { e.printStackTrace(); return "图片上传失败!"; } } String imagePath = "http://localhost:8888/static/img/" + imageName; return imagePath; }

    上面的newCompanyImagePath 就是该项目中存放图片的文件夹的绝对路径 项目结构如下: 还有一个问题就是新上传一张图片之后,回显会失败,要刷新后端项目img文件夹,重新运行项目才能显示出来,怎么解决这个问题呢? 这里我们可以通过虚拟路径映射的方法来解决。 在后端项目中添加一个类:

    //新增加一个类用来添加虚拟路径映射 @Configuration public class MyPicConfig implements WebMvcConfigurer{ @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/static/img/**") .addResourceLocations("file:D:/Program Files (x86)/workspace-spring-tool-suite-4-4.6.2.RELEASE/csi/src/main/resources/static/img/"); } }
    Processed: 0.037, SQL: 8