您的位置:首页 > 其它

旅游项目(三)ssm实现文件上传下载实操

2017-09-19 10:17 393 查看
用户通过浏览器以multipart格式上传到服务器后,业务层代码:

public boolean uploadObject(String title, MultipartFile mFile) throws IOException {
//1.判断文件合法
if(StringUtils.isEmpty(title)) throw new InputInvalidException("标题不能为空");
if(mFile==null|| mFile.isEmpty()) throw new InputInvalidException("文件对象不能为空");
//2.计算文件摘要
String fileDigest = DigestUtils.md5DigestAsHex(mFile.getBytes());
//3.根据摘要查询数据库
Attachment attachment = attachmentDao.findObjectByDigest(fileDigest);
//发现该摘要,则提示已经上传
 if(attachment!=null) throw new FileUploadException("文件已上传");
//4.如果木有则执行上传
//文件夹以日期形式构建
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
String destDir="d:/upload/"+sdf.format(new Date())+"/";
//文件名前拼接UUID以防重名
String newName=UUID.randomUUID().toString();
String fileName = mFile.getOriginalFilename();
//取文件格式
String ext = fileName.substring(fileName.lastIndexOf("."));
String destFileName=newName+ext;
//新建文件
File dest = new File(destDir,destFileName);
//构建文件夹目录
File parent = dest.getParentFile();
if(!parent.exists()) parent.mkdirs();
mFile.transferTo(dest);
Attachment newAttachment = new Attachment();
newAttachment.setTitle(title);
newAttachment.setFileName(mFile.getName());
newAttachment.setFilePath(dest.getAbsolutePath());
newAttachment.setContentType(mFile.getContentType());
newAttachment.setFileDigest(fileDigest);
int n = attachmentDao.insertObject(newAttachment);
if(n!=1) throw new RuntimeException("插入失败!");
//5.将文件信息写到数据库中
return true;
}

和如何将保存好的文件转成byte数组形式返回给浏览器:

@RequestMapping("doDownload")
@ResponseBody
public byte[] downloadObjects(String fileDigest,HttpServletResponse response) throws IOException{
Attachment attachment = attachmentService.findObjectByDigest(fileDigest);
//设置响应类型和响应头
response.setContentType("application/octet-stream");
//设置响应头时要注意中文文件名的处理!!!
 response.setHeader("Content-disposition", "attachment;filename="+URLEncoder.encode(attachment.getFileName(), "utf-8"));
//根据文件路径获得一个path对象
Path path = Paths.get(attachment.getFilePath());
//nio里面另外一个类用来读取path里面的字节数
return Files.readAllBytes(path);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: