记录Java 文件(图片)上传的几种实现

在项目应用中,经常会用到图片或文件上传的功能,需要我们提供接口给web,app,微信或其他系统调用,下面列出几种方式供小伙伴参考:

1、MultipartFile:图片上传在应用中经常会用到MultipartFile来接收,代码如下:

@RequestMapping("/imageUpload.do")
public Map imageUpload(@RequestParam("file") MultipartFile multipartFile)  {
    String fileSavePath=shoesImagePath;
    if (null == multipartFile || multipartFile.getSize() <= 0) {
        return new HashMap(){{put("code",400);put("msg","请选择上传文件。");}};
    }
    //文件名
    String originalName = multipartFile.getOriginalFilename();
    String fileName= UUID.randomUUID().toString().replace("-", "");
    String picNewName = fileName + originalName.substring(originalName.lastIndexOf("."));
    String imgRealPath = fileSavePath + picNewName;
    try {
        //保存图片-将multipartFile对象装入image文件中
        File imageFile=new File(imgRealPath);
        multipartFile.transferTo(imageFile);
    } catch (Exception e) {
        return new HashMap(){{put("code",400);put("msg","图片保存异常:"+e);}};
    }
    return new HashMap(){{put("code",200);put("msg",picNewName);}};
}

启动后台应用后,用postman调用试试:

记录Java 文件(图片)上传的几种实现_第1张图片

另外,MultipartFile 还有另外一种写法,在上传接口中未显示指明接收参数名,这时候我们需从HttpServletRequest参数中获取,具体代码如下:

@RequestMapping("/imageUploadSec.do")
public Map imageUploadSec(HttpServletRequest request)  {
    //将HttpServletRequest参数转成StandardMultipartHttpServletRequest 类型
    StandardMultipartHttpServletRequest stRequest = (StandardMultipartHttpServletRequest)request;
   //获取multipartFiles 对象组
    MultiValueMap multipartFiles = stRequest.getMultiFileMap();
    //获取MultipartFile 文件对象
    MultipartFile multipartFile=multipartFiles.getFirst("file");
    if (null == multipartFile || multipartFile.getSize() <= 0) {
        return new HashMap(){{put("code",400);put("msg","请选择上传文件。");}};
    }
    String fileSavePath=shoesImagePath;
    String originalName = multipartFile.getOriginalFilename();
    String fileName= UUID.randomUUID().toString().replace("-", "");
    String picNewName = fileName + originalName.substring(originalName.lastIndexOf("."));
    String imgRealPath = fileSavePath + picNewName;
    try {
        File imageFile=new File(imgRealPath);
        multipartFile.transferTo(imageFile);
    } catch (Exception e) {
        return new HashMap(){{put("code",400);put("msg","图片保存异常:"+e);}};
    }
    return new HashMap(){{put("code",200);put("msg",picNewName);}};
}

2、另外,我们也可以接收basic64位格式的图片数据流,并解码将其转换成图片保存:

/**
 * 接收basic64格式图片数据流保存成图片
 * @param pImgData
 * @return
 */
@RequestMapping("/basic64ImageUpload.do")
public Map basic64ImageUpload(@RequestParam("pImgData") String  pImgData) {
    if(StringUtils.isEmpty(pImgData)){
        return new HashMap(){{put("code",400);put("msg","请选择上传图片。");}};
    }
    try {
        this.saveBase64Image(pImgData.replaceAll(" ", "+").split("base64,")[1], shoesImagePath + "//test.jpg");
    } catch (Exception e) {
        e.printStackTrace();
    }
    return new HashMap(){{put("code",200);put("msg","test.jpg");}};
}

//解码basic64格式图片数据流,保存成图片

public static String saveBase64Image(String base64Image, String imageFilePath) {
    if (base64Image == null) {
        return "图像数据不能为空";
    } else {
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            File imageFile = new File(imageFilePath);
            if (imageFile.exists()) {
                imageFile.delete();
            }
            byte[] b = decoder.decodeBuffer(base64Image);

            for(int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] = (byte)(b[i] + 256);
                }
            }
            OutputStream out = new FileOutputStream(imageFilePath);
            out.write(b);
            out.flush();
            out.close();
            return "";
        } catch (Exception var6) {
            return var6.toString();
        }
    }
}

以上就是常用的两种图片上传方式,是不是非常简单,如果有好的方式,小伙伴们可以在评论区探讨哦!!

 

 

你可能感兴趣的:(记录Java 文件(图片)上传的几种实现)