前言
记录java文件上传和下载。
一、文件上传
@PostMapping("/upload")
public Result upload(@ApiParam(name = "file", value = "文件", required = true)
@RequestParam(name = "file",required = false) MultipartFile file){
String fileName = file.getOriginalFilename();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();
String dateStr = sdf.format(date);
String fullPath = fliePath + dateStr + "-" + fileName;
File dest = new File(fullPath);
try {
file.transferTo(dest);
return new Result(ResultEnum.SUCCESS);
} catch (IOException e) {
e.printStackTrace();
return new Result(ResultEnum.ERROR);
}
}
二、java图片转BASE64
@RequestMapping(value = "/getImage", method = RequestMethod.POST)
public Result getImage(@RequestBody Imgurl imgurl) throws IOException {
String url=imgurl.getUrl();
FileInputStream fileInputStream = new FileInputStream(url);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int len = -1;
while((len = fileInputStream.read(b)) != -1) {
bos.write(b, 0, len);
}
byte[] fileByte = bos.toByteArray();
//进行base64位加密
BASE64Encoder encoder = new BASE64Encoder();
String data = encoder.encode(fileByte);
return new Result(ResultEnum.SUCCESS,data);
}
三、java下载文件
@RequestMapping(value = "/getDownLoad", method = RequestMethod.POST)
public void getDownLoad(HttpServletResponse response,@RequestBody Imgurl imgurl) throws IOException {
FileInputStream inputStream = null;
try{
File file = new File(imgurl.getUrl());
inputStream = new FileInputStream(file);
ByteArrayOutputStream os = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) != -1) {
os.write(buffer, 0, length);
}
byte[] data = os.toByteArray();
response.resetBuffer();
response.resetBuffer();
response.setHeader("Content-Disposition", "attachment");
response.addHeader("file-name",URLEncoder.encode(imgurl.getName(), "UTF-8"));
response.addHeader("Content-Length", "" + data.length);
response.setContentType("application/octet-stream; charset=UTF-8");
IOUtils.write(data,response.getOutputStream());
}
catch (IOException e)
{
e.printStackTrace();
}
finally {
if(inputStream != null)
{
inputStream.close();
}
}
}