一、上传图片
我这边封装了好几层,我把用到的代码黏贴出来
@PostMapping("/uploadLanguageImage")
public R uploadLanguageImage(@RequestParam("file") MultipartFile file) {
return R.ok().put("url", IOUtil.languageImageFileOut(file));
}
IOUtil工具类 用到的代码
public static String languageImageFileOut(MultipartFile file) {
return imageFileOut(file, Constant.UploadPath.LANGUAGE_UPLOAD.getValue());
}
public static String imageFileOut(MultipartFile file, String path) {
String fileName = createFileName(null);
return imageFileOutReImagePath(file, path, fileName);
}
public static String imageFileOutReImagePath(MultipartFile file, String path, String fileName) {
return imageFileOut(file, path, fileName, Constant.UploadPath.GET_IMAGE.getValue());
}
public static String imageFileOut(MultipartFile file, String path, String fileName, String interfacePrefix) {
String filePath = path + fileName;
dirCreate(path);
try {
file.transferTo(new File(filePath));
return interfacePrefix + filePath;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
二、下载图片
1.我封装了好几层,我用的访问图片的接口是全局的,如上getImage,代码如下
@GetMapping(value = "/getImage", produces = {MediaType.IMAGE_JPEG_VALUE})
public byte[] getHeader(@RequestParam("path") String path) {
return IOUtil.responseImage(path);
}
public static byte[] responseImage(String pathImage) {
try {
File file = new File(pathImage);
FileInputStream inputStream = new FileInputStream(file);
byte[] bytes = new byte[inputStream.available()];
inputStream.read(bytes, 0, inputStream.available());
return bytes;
} catch (IOException e) {
new SFException("获取文件失败");
}
return null;
}
三、上传文件
其实上传文件,无论是pdf,还是word 等等,用上传图片那种方式就可以 就是生成文件名的时候把后缀名换一下,根据需求而来
四、下载文件
这里下载文件有一点不同的是,图片和文件都是强制下载,不能在浏览器跳转页面预览,和上面的下载图片不一样,那个下载图片的是把图片放到byte数组里面通过spring 返回给响应出去 如果要强制下载,就要用到下面的方式 我这边接口名字是getFile,是因为我有两个枚举 GET_IMAGE("/hireinfo/entry/getImage?path="),//获取图片 GET_FILE("/hireinfo/entry/getFile?path="),//获取文件 是在上传的时候,用到的访问路径前缀
@GetMapping(value = "/getFile")
public void getFile(@RequestParam("path") String path, HttpServletResponse response) {
try {
File file = new File(path);
String newFileName = System.currentTimeMillis() + "." + StringUtil.getFileNameSuffix(path);
InputStream inputStream = new FileInputStream(file);
response.setContentType("application/force-download");
OutputStream out = response.getOutputStream();
response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(newFileName, "UTF-8"));
int b = 0;
byte[] buffer = new byte[1000000];
while (b != -1) {
b = inputStream.read(buffer);
if (b != -1) out.write(buffer, 0, b);
}
inputStream.close();
out.close();
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
|