前言
在做的项目要求实现自动更新,因此首先要实现文件上传到服务器某个路径和从服务器上下载,故在此做一个记录
一、上传文件
1.Controller层
@Autowired
private FileService fileService;
@Value("${path.app}")
private String OTHER_UPLOAD_PATH;
@Value("${path.picture}")
private String PICTURE_UPLOAD_PATH ;
//上传接口,isPicture只是简单分类一下是否为图片,之后可以改成传入一个字符串对应到不同的路径上
@PostMapping(value = "/uploadFile",consumes= MediaType.MULTIPART_FORM_DATA_VALUE)
public R upload(@RequestParam("file") MultipartFile file, Boolean isPicture) throws Exception {
if(isPicture){
return fileService.upload(file,PICTURE_UPLOAD_PATH,isPicture);
}
return fileService.upload(file,OTHER_UPLOAD_PATH,isPicture);
}
2.Service层
@Autowired
SnowflakeUtil snowflakeUtil;
@Value("${server.port}")
private String port;
@Value("${server.ip}")
private String ip;
//上传接口的实现
@Override
public R upload(MultipartFile file, String uploadFilePath, Boolean isPicture) throws Exception {
//如果文件为空则返回
if (file.isEmpty())
return null;
UploadInfo uploadInfo = new UploadInfo();
String originalFilename;
String originalFilenameWithoutSuffix="";
String fileName;
String suffix;
//获取上传的文件名字(带后缀)
originalFilename = file.getOriginalFilename();
//获取上传的文件名字(不带后缀)
for(int i=0;i<originalFilename.split("\\.").length-1;i++) {
originalFilenameWithoutSuffix += originalFilename.split("\\.")[i] + ".";
}
//获取文件后缀
suffix = originalFilename.split("\\.")[originalFilename.split("\\.").length-1];
//上传到服务器的文件名字
fileName = originalFilenameWithoutSuffix + UUID.randomUUID().toString() + '.' + suffix;
//获取文件类型
String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
//获取文件大小
long fileSize = file.getSize();
File packageFile = new File(uploadFilePath);
if (!packageFile.exists()) {
packageFile.mkdir();
}
File targetFile = new File(uploadFilePath + "/" + fileName);
file.transferTo(targetFile);
//设置返回信息
uploadInfo.setId(snowflakeUtil.getSnowflakeId());
uploadInfo.setBeginFileName(originalFilename);
uploadInfo.setLastFileName(fileName);
uploadInfo.setFileType(fileType);
uploadInfo.setFileSize(Long.toString(fileSize));
uploadInfo.setUploadUrl(targetFile.toString());
//构造访问链接
if(isPicture)
{
uploadInfo.setVisitUrl("http://" + ip + ":" + port + "/file/images/" + uploadInfo.getLastFileName());
}else{
uploadInfo.setVisitUrl("http://"+ip+":"+port+"/file/"+uploadInfo.getLastFileName());
}
//构造下载链接
uploadInfo.setDownloadUrl("http://" + ip + ":" + port + "/file/download?fileName=" + uploadInfo.getLastFileName() + "&isPicture=" + isPicture);
uploadInfo.setResult("上传成功");
//将下载记录存入数据库
baseMapper.record(uploadInfo);
return R.ok().message("成功").data("info",uploadInfo);
}
二、下载
1.Controller层
//下载接口,在构造下载链接时用到
@RequestMapping("/download")
@ResponseBody
public void download(HttpServletResponse response,String fileName,Boolean isPicture) throws UnsupportedEncodingException {
if(isPicture){
fileService.download(response, PICTURE_UPLOAD_PATH, fileName,isPicture);
}else{
fileService.download(response, OTHER_UPLOAD_PATH, fileName,isPicture);
}
}
2.Service层
@Override
public void download(HttpServletResponse response, String path, String fileName, Boolean isPicture) throws UnsupportedEncodingException {
//文件的位置
String FullPath = path + fileName;
File packetFile = new File(FullPath);
//下载的文件名
String fn = packetFile.getName();
System.out.println("filename:"+fn);
File file = new File(FullPath);
// 如果文件名存在,则进行下载
if (file.exists()) {
// 配置文件下载
response.setHeader("content-type", "application/octet-stream");
response.setContentType("application/octet-stream");
// 下载文件能正常显示中文
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
// 实现文件下载
byte[] buffer = new byte[1024];
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
OutputStream os = response.getOutputStream();
int i = bis.read(buffer);
while (i != -1) {
os.write(buffer, 0, i);
i = bis.read(buffer);
}
System.out.println(response.getWriter());
System.out.println("下载成功");
} catch (Exception e) {
System.out.println("mistake:"+e.getMessage());
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} else {
//对应文件不存在
System.out.println("文件不存在");
return;
}
}
注意下载链接只能在浏览器内测试,这样才会直接下载,直接用postman会看到返回的乱码