vue直接上传图片

页面:

js:

methods:{
    //上传图片
    onUpload:function(e){
        var file2 = e.target.files[0];
        api.upload(file2).done(function(res){//封装的请求接口api.js文件
            if(res.result.code == 0){
                console.log(res);
            }
        });
    },

}

api.js(与java后台接口对接):

api.uploadImg = function (url, data) {

    return $.ajax({
        url: url,
        data: data,
        dataType: "json",
        method: "post",
        contentType: false,cache: false,
        processData: false
    });
}
//上传图片
api.upload = function (file2) {
    var url = root + "/upload/img?";//后台接口
    var data = new FormData();
    data.append("file",file2);
    data.append("pathType",4)
    return api.uploadImg(url, data);
}

 

后端:

   /**
    * 上传图片
    * @param servletRequest
    * @param file
    * @return
    * @throws Exception
    */
   @ApiOperation(value = "上传图片",notes = "upload")
   @ApiImplicitParam(name="pathType",value="图片类型:1广告图片,2商品图片,3头像图片,4公司logo",required=true, dataType = "Integer", paramType = "Integer")
   @RequestMapping(value = "/upload/img", method = RequestMethod.POST, headers = "content-type=multipart/form-data",produces="application/json;charset=UTF-8")
   @ResponseBody
   public String upload(HttpServletRequest servletRequest,
                     @ApiParam(value = "上传的文件", required = true)
                   @RequestParam(value = "file", required = true) MultipartFile file,
                     @RequestParam(value = "pathType", required = true) Integer pathType
   ) throws Exception {
      Response response = new Response(true);
      Result result = new Result();
      try {
         //如果文件内容不为空,则写入上传路径
         if (!file.isEmpty()) {
            //上传文件路径
            String[] pathArray=getPath(pathType);
            //上传文件名
//          String filename = file.getOriginalFilename();
            String filename = createFileName(file.getOriginalFilename(),pathType);
            logger.info("文件原名称:" + file.getOriginalFilename()+",文件新名称:" + filename);
            File filepath = new File(pathArray[0], filename);


            //判断路径是否存在,没有就创建一个
            if (!filepath.getParentFile().exists()) {
               filepath.getParentFile().mkdirs();
            }

            //将上传文件保存到一个目标文档中
            File file1 = new File(pathArray[0] + FilePathUtil.FILE_SEPARATOR + filename);
            file.transferTo(file1);
            String path =pathArray[1]+"/"+filename;
            ImgTemp imgTemp = new ImgTemp();
            imgTemp.setPicPath(path);
            imgTemp.setCreateDateStr(DateHelper.getCurDate());
            imgTemp.setStatus(Constants.IMG_TEMP_STATUS_TEMP);
            int i =fileUploadService.add(imgTemp);
            if(i==0){
               throw new ProjectException(Constants.Return.SAVE_FILE_PATH_ERROR);
            }
            result.getData().put("path",path);
         }
      }catch (ProjectException e){
         result.setState(e.getError());
      }catch(Exception e){
         logger.error(e.getMessage(), e);
         result.setState(new ProjectException(Constants.Return.FILE_UPLOAD_ERROR, e.getMessage()));
      }
      response.setResult(result);
      return response.toJson();
   }

   /**
    * 生成新文件名称
    * @param originalFilename
    * @param pathType
    * @return
    */
   private String createFileName(String originalFilename, Integer pathType) {
      String originalFileName=originalFilename;
      //新图片名:图片类型+年月日时分秒毫秒+4位随机数字
      String filename = getPre(pathType)
                          +DateHelper.getStrDate4Date(new Date(),DateHelper.TIME_FORMAT12)
                          + VerifyCodeUtil.generateVerifyCode(4)
                          +originalFileName.substring(originalFileName.lastIndexOf("."),originalFileName.length());
      if(fileUploadService.checkExists(filename)){
         return createFileName(originalFilename,pathType);
      }else{
         return filename;
      }
   }


   /**
    * 生成保存路径和访问路径
    * @param i
    * @return
    */
   private String[] getPath(int i){
      String[] pathArray= new String[2];
      String dateStr = DateHelper.getCurDate();
      String path = uploadFolder+ FilePathUtil.FILE_SEPARATOR+getPre(i)+ FilePathUtil.FILE_SEPARATOR+dateStr;
      pathArray[0]=path;
      String staticPath = staticAccessPath.substring(0,staticAccessPath.lastIndexOf("/"))+"/"+getPre(i)+"/"+dateStr;
//    String staticPath = staticAccessPath+"/"+(i==1?"ad":(i==2?"commodity":"avator"))+"/"+dateStr;
      pathArray[1]=staticPath;
      return pathArray;
   }

   /**
    * 获取前缀
    * @param i
    * @return
    */
   private String getPre(int i){
      return i==1?"ad":(i==2?"commodity":(i==3?"avator":"company"));
   }
   /**
    * 删除未使用图片文件
    * @param servletRequest
    * @param startDateStr
    * @param endDateStr
    * @return
    * @throws Exception
    */
   @ApiOperation(value = "删除未使用图片文件",notes = "deleteUnusedPic")
   @ApiImplicitParams({
         @ApiImplicitParam(name="startDateStr",value="开始日期",required=true, dataType = "String", paramType = "String",example = "2019-01-23"),
         @ApiImplicitParam(name="endDateStr",value="结束日期",required=true, dataType = "String", paramType = "String",example = "2019-01-23")
   }
   )

   @RequestMapping(value = "/delete/img/unused", method = RequestMethod.POST, headers = "content-type=multipart/form-data",produces="application/json;charset=UTF-8")
   @ResponseBody
   public String deleteUnusedPic(HttpServletRequest servletRequest,
                          @RequestParam(value = "startDateStr", required = true) String startDateStr,
                          @RequestParam(value = "endDateStr", required = true) String  endDateStr
   ) throws Exception {
      Response response = new Response(true);
      Result result = new Result();
      try {
         fileUploadService.deleteUnusedPic(startDateStr,endDateStr);
      }catch (ProjectException e){
         result.setState(e.getError());
      }catch(Exception e){
         logger.error(e.getMessage(), e);
         result.setState(new ProjectException(Constants.Return.FILE_DELETE_ERROR, e.getMessage()));
      }
      response.setResult(result);
      return response.toJson();
   }

这里我们要注意的是后端接受请求的参数格式(非常重要!!!)

你可能感兴趣的:(前端)