旅游项目(三)ssm实现文件上传下载实操
2017-09-19 10:17
393 查看
用户通过浏览器以multipart格式上传到服务器后,业务层代码:
和如何将保存好的文件转成byte数组形式返回给浏览器:
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); }
相关文章推荐
- springmvc文件上传下载简单实现案例(ssm框架使用)
- springmvc文件上传下载简单实现案例(ssm框架使用)
- 项目开发技巧(四):使用JspSmartupload实现文件上传下载(二):jspSmartUpload上传下载全攻略(ZZ)
- SSM实现文件的上传和下载
- JavaWeb实现文件上传下载功能实例解析以及项目工程示例下载
- springmvc文件上传下载简单实现案例(ssm框架使用)
- Java - 如何在基于Java的Web项目中实现文件上传和下载?
- 项目开发技巧(四):使用JspSmartupload实现文件上传下载(三):jspsmartupload samples
- 项目开发技巧(四):使用JspSmartupload实现文件上传下载(一):JspSmart之upload组件源码及使用
- SSM框架下实现文件的上传和下载
- linux项目:在linux下实现文件的上传与下载工作
- springmvc文件上传下载简单实现案例(ssm框架使用)
- SSM实现文件上传下载总结
- 无组件实现文件上传/下载
- ASP.NET实现文件的上传与下载(包括用数据库存取文件)
- 无组件实现文件上传/下载
- Asp.net中文件上传下载的简单实现
- Asp.net 2.0 用 FileUpload 控件实现多文件上传 用户控件(示例代码下载).NET技术
- jsp实现文件上传下载功能
- Asp.net 2.0 用 FileUpload 控件实现多文件上传 用户控件(示例代码下载)