java项目附件的上传下载
文件上传:
将文件上传到服务器指定目录下,根据当前日期创建文件夹目录,文件采用uuid命名。将文件名和保存的路径存入数据库中。
@Controller
@RequestMapping("/attachment")
public class AttachmentController {
@Value("${upload.path}")
private String uploadPath;
private Logger log = Logger.getLogger(this.getClass());
@Autowired
BasAttachmentService attachmentService;
/**
* 上传单个附件文件
*/
@ResponseBody
@RequestMapping(value = "/uploadOne", method = RequestMethod.POST)
public Object uploadOne( @RequestParam("file") MultipartFile partFile, HttpServletRequest request) {
//根据当前时间获得一个路径
StringBuilder path=new StringBuilder();
Date data=new Date();
path.append("//").append(DateUtil.format(data, "yyyy"));
path.append("//").append(DateUtil.format(data, "MM"));
path.append("//").append(DateUtil.format(data, "dd"));
String time=DateUtil.format(data,"yyyyMMdd");
path.append("//").append(time);
String uuid = UUID.randomUUID().toString().replaceAll("-","");
path.append(uuid);
File file= new File(uploadPath+path);
try {
InputStream inputStream = partFile.getInputStream();//获取文件流
FileUtils.copyInputStreamToFile(inputStream, file);//将文件拷贝到指定目录下
} catch (IOException e) {
e.printStackTrace();
return PageReturn.fail("获取文件流异常");
}
String fileName = partFile.getOriginalFilename();//上传的文件名称
BasAttachment attachment=new BasAttachment();
attachment.setName(fileName);
attachment.setFileName(time+uuid);
attachment.setFilePath(path.toString());
attachment.setFileSize(file.length());
attachment.setCreateTime(new Date());
attachmentService.save(attachment);
return PageReturn.successData(attachment);
}
}
下载文件:
通过文件名从数据库中找到附件对象,根据存储的路径找到对应的文件,将文件进行下载。
/**
* 下载单个文件
*/
@ResponseBody
@RequestMapping(value = "/downLoad/{fileName}")
public void downSingle(HttpServletRequest request, HttpServletResponse response, @PathVariable(value = "fileName") String fileName) {
if(StringUtil.isEmpty(fileName))throw new MyException("文件名字不能为空");
BasAttachment attachment=attachmentService.findByFileName(fileName);
if(attachment==null) throw new MyException("文件名称错误");
String name=attachment.getName();
String filePath=attachment.getFilePath();
File file=new File(uploadPath+filePath);
try {
String userAgent = request.getHeader("user-agent").toLowerCase();
String downloadFileName;
if (userAgent.contains("msie") || userAgent.contains("like gecko") ) {
// win10 ie edge 浏览器 和其他系统的ie
downloadFileName = URLEncoder.encode(name, "UTF-8");
} else {
// fe
downloadFileName = new String(name.getBytes("UTF-8"), "iso-8859-1");
}
response.addHeader("content-disposition", "attachment;filename="+downloadFileName);
FileUtils.copyFile(file, response.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
throw new MyException("下载附件异常");
}
}
项目代码见:
https://github.com/wxb100200/wang-base.git

浙公网安备 33010602011771号