springboot上传图片

1.先配置初始化参数,yml或类里配置图片存放的真实路径和映射路径
2.在dao层写保存图片的接口
3.在controller中,前台传过来的MultipartFile file中,包含了上传过来的图片及其他字段
4.WebMvcConfig.java   是为了将真实路径的地址映射到http上面
5.在vue里上传图片及其他字段

Controller
--updateProductOneById.java
Dao
--updateProductOneById.java
Commons
--contants
----contant.java
Filter
--WebMvcConfig.java

SaveImage.java   //保存图片代码

@CrossOrigin
public class SaveImage {
    @Autowired
    private static ImgService imgService;
    public static String ReturnHttpURL(MultipartFile file, HttpServletRequest request)throws IOException{
        String httpUrl="";
        //获取文件名
        String filename = file.getOriginalFilename(); //图片名
        String[] split = new String[0];
        if (filename != null) {
            split = filename.split("\\.");
        }
        //只接受jpg、png、jpeg格式图片文件,其它格式的文件可按需添加判断,主要是为了防止上传恶意文件,加强安全性
        if ("jpg".equalsIgnoreCase(split[1]) || "png".equalsIgnoreCase(split[1]) || "jpeg".equalsIgnoreCase(split[1])) {
            //图片重命名加后缀
            String photoName = UUID.randomUUID().toString().replace("-", "") + "." + split[1];
            File destFile = new File(Contant.FILE_REALFOLDER + File.separator + photoName);
            //判断是否存在, 不存在就创建
            if (!destFile.getParentFile().exists()) {
                destFile.getParentFile().mkdirs();
            }
            //压缩图片保存
            Thumbnails.of(file.getInputStream()).scale(0.8).toFile(destFile);
            //获取协议、服务器IP、端口号、工程路径
            String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
            httpUrl = basePath + Contant.FILE_REFLEXFOLDER + photoName;
            System.out.println("------------------------------------"+httpUrl);
        }

        return httpUrl;
    }
}



Contant.java

public class Contant {

    public static final  String FILE_REALFOLDER= "E://IdeaProjects/Projects/shop/src/main/resources/static/images";
    public static final  String FILE_REFLEXFOLDER= "/upload/logo/";
}


Controller.java      
 

@RequestMapping(value = "page/seller/updateProductOneById",method = RequestMethod.POST)
    @ResponseBody
    public ReturnObject updateProductOneById(Product product, MultipartFile file, HttpServletRequest request) throws IOException {
        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
        String tname = (String) multipartHttpServletRequest.getParameter("product");
       
        JSONObject jsonObject = JSONObject.parseObject(tname);
        String id = jsonObject.getString("id");
        String name = jsonObject.getString("name");
     
        product.setId(id);
        product.setName(name);
       

        ReturnObject returnObject = new ReturnObject();
        returnObject.setCode(Contant.RETURN_OBJECT_CODE_FAIL);
        returnObject.setMsg("请上传文件后重试");

        if (file != null && !file.isEmpty()) {
            String httpUrl = SaveImage.ReturnHttpURL(file, request);
            product.setProductpicture(httpUrl);
            int count = productService.updateProductOneById(product);
            if (count > 0) {
                returnObject.setCode(Contant.RETURN_OBJECT_CODE_SUCCESS);
                returnObject.setMsg("修改成功");
                returnObject.setReturnObjectData(count);
            }else{
                returnObject.setCode(Contant.RETURN_OBJECT_CODE_FAIL);
                returnObject.setMsg("修改失败");
            }

        }
        return returnObject;
    }


WebMvcConfig.java    //映射地址

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
   
    private String logoRealFolderPath=Contant.FILE_REALFOLDER;
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
    //将真实地址映射到http上
    //addResourceHandler("存放想要映射到http上的路径    //eg:http://localhost:8080/upload/logo/1.jpg")

    //addResourceLocations("存放图片的真实路径",eg:"E:/image/");
        registry.addResourceHandler("/upload/logo/**").addResourceLocations("file:"+logoRealFolderPath+"/");
    }
}

index.vue

                                                                                                                                                                                                                      取 消     确 定     确 定          


index.js

method:{  
productUpdata(formName){
      let data = {
        id:this.edit.id,
        name : this.edit.name,
      }
      let datas = JSON.stringify(data)
    //传图片
      this.$refs[formName].validate(valid => {
        if (valid && this.fileList.length>0) {
          let formData = new FormData();
          for (let i = 0; i < this.fileList.length; i++) {
            formData.append("file", this.fileList[i].raw, this.fileList[i].name);
          }
          formData.append("product",datas)
          const http1 = this.$axios.create({
            headers: {
              "Content-Type": "multipart/form-data"
            }
          })
          http1({
            url: "http://localhost:8080/page/seller/updateProductOneById",
            method: 'post',
            data: formData
          }).then((res) => {

            this.$message({
              message: "修改成功",
              type: "success"
            })
            this.dialogVisible = false
            this.getDateShow()
          })
              .catch(() => {
                this.$message({
                  message: "请求超时,请检查网络连接",
                  type: "error"
                })
              });
        }
      });
    }

data{
    return{

    form: {
        tname: '',
        detail: ''
      },
      //用来绑定加入的图片,后续用大图片预览
      dialogImageUrl: '',
      //用来接收缓存中的图片
      fileList: [],
}

}
}


 

你可能感兴趣的:(spring,boot,java,后端)