vue图片上传

1.首先我们需要取消文件的自动上传功能 :isXhr="false"。后台使用的是springboot接收具体代码下面会给出

     组件整体代码

<vue-core-image-upload
  class="btn btn-primary"
  :crop="false"
  @imagechanged="add"
  :max-file-size="5242880"
  :isXhr="false"
  :multiple="true"
  url="">
  <img width="80%;" src="../assets/img/ting.jpg"/>
</vue-core-image-upload>

2.需要进行操作后再将数据传递后台:

var form=new FormData();
this.file.forEach(function (value,index,array) {
  form.append("file",value);
});
    这边我再添加图片添加了  @imagechanged方法,将图片存入数组,在上传时进行转换放入formdata中,上传是我设置了请求头格式:
let uploadConfig = {
  headers: {
    'Content-Type': 'multipart/form-data;charset=UTF-8'
  }
};

3.下面是后台接收代码:(使用springboot)

@RequestMapping(value = "/upload2")
@ResponseBody
public Map upload2(HttpServletRequest request,HttpServletResponse response) throws IOException {
    List<MultipartFile> files = ((MultipartHttpServletRequest) request)
            .getFiles("file");
    Map map = new HashMap();
    map.put("code",1);

    String url = "";
    String msg = "";
    MultipartFile file = null;
    BufferedOutputStream stream = null;
    for (int i = 0; i < files.size(); ++i) {
        file = files.get(i);
        if (!file.isEmpty()) {

            String path = null; //文件路径
            String type = null;// 文件类型
            String fileName = file.getOriginalFilename();// 文件原名称
            logger.info("上传的源文件名称为----------" + fileName);
            // 判断文件类型
            type = fileName.indexOf(".") != -1 ? fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()) : null;
            if (type != null) {// 判断文件类型是否为空
                if ("JPEG".equals(type.toUpperCase()) || "GIF".equals(type.toUpperCase()) || "PNG".equals(type.toUpperCase()) || "JPG".equals(type.toUpperCase())) {
                    // 项目在容器中实际发布运行的根路径
                    String realPath = request.getSession().getServletContext().getRealPath("/");
                    // 自定义的文件名称
                    String trueFileName = String.valueOf(System.currentTimeMillis()) + fileName;
                    // 设置存放图片文件的路径
                    path = "F:\\Code\\SmartParking-wechat\\src\\assets\\img\\" +trueFileName;
                    logger.info("存放图片文件的路径:" + path);
                    // 转存文件到指定的路径
                    file.transferTo(new File(path));
                    logger.info("文件成功上传到指定目录下");
                    url= trueFileName;
                } else {
                    logger.info("不是我们想要的文件类型,请按要求重新上传");
                    msg= "不是我们想要的文件类型,请按要求重新上传";
                }
            } else {
                logger.info("文件类型为空");
                msg= "文件类型为空";
            }
        } else {
            logger.info("没有找到相对应的文件");
            msg= "没有找到相对应的文件";


        }
    }
   map.put("url",url);
    map.put("msg",msg);
    return map;
}


 
 
 
 

猜你喜欢

转载自blog.csdn.net/wanjunsnow/article/details/79820316