javaweb项目中的文件上传下载功能的实现
框架是基于spring+myBatis的。
前台页面的部分代码:
<form action="${ctx}/file/upLoadFile.do"method="post" enctype="multipart/form-data" id="form"><table><tbody ><tr ><td>上传文件:</td><td style="padding-left: 10px;"><input type="file" name="file" id="fileInput"></td><td style="padding-left: 80px;"><button type="submit" class="btn btn-primary btn-q btn-outline fa fa-upload" class="easyui-validatebox" data-options="required:true">上传</button></td></tr><tr><td colspan="2"><span style="color:red">*上传文件格式为xls,xlsx,txt,csv文件!</span> </td> </tr> </tbody>
</table></form>
{ title : '操作', halign : 'center', align : 'center', width : 80, field : 'FILE_PATH', formatter: function(value,row,index){ var path = "${ctx}/file/download.do?filePath=" + value ; var button = '<button type="button" class="btn btn-primary btn-q btn-outline fa fa-download" class="easyui-validatebox"
data-options="required:true">下载</button>'; return "<a href='" + path + "'>" + button + "</a>";
}
上传功能的方法:
@RequestMapping("/upLoadFile") public String upload(@RequestParam(value = "file", required = false) MultipartFile file, ModelMap model, HttpServletRequest request)
throws Exception {
//设置相对路径 String realPath = request.getSession().getServletContext().getRealPath("/upload");
//获取文件的格式 String extention = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1);
//对格式进行筛选 if(extention.equalsIgnoreCase("xls") || extention.equalsIgnoreCase("xlsx") || extention.equalsIgnoreCase("txt")
|| extention.equalsIgnoreCase("csv")) {
//在路径下创建文件夹 File f = new File(realPath); String fileName = file.getOriginalFilename(); String uploadPath = realPath + File.separator + fileName; if(!f.exists()) { f.mkdir(); }
//文件的传输 file.transferTo(new File(uploadPath)); Upload upload = new Upload(); upload.setFileName(fileName); upload.setFileLength(String.valueOf(file.getSize())); upload.setFileOwner(super.getLoginUser(request).getLoginId()); upload.setFilePath("/upload/" + fileName);
//将文件的基本信息存到数据库 fileQueryService.saveFile(upload); request.setAttribute("info","文件上传成功!"); } else { request.setAttribute("info","文件类型不正确,请上传格式为xls,xlsx,txt,csv文件!"); } return "page/file/fileInteraction"; }
下载功能的方法:
@RequestMapping("/download") public String download(String filePath, HttpServletRequest request, HttpServletResponse response) { try {
//获取文件名 String fileName = filePath.substring(filePath.lastIndexOf("/")+1); System.out.println(filePath); response.setCharacterEncoding("utf-8"); response.setContentType("multipart/form-data");
//处理下载弹出框名字的编码问题 response.setHeader("Content-Disposition", "attachment;fileName=" + new String( fileName.getBytes("gb2312"), "ISO8859-1" )); //获取文件的下载路径 String path = request.getSession().getServletContext().getRealPath(filePath); System.out.println(path);
//利用输入输出流对文件进行下载 InputStream inputStream = new FileInputStream(new File(path)); OutputStream os = response.getOutputStream(); byte[] b = new byte[2048]; int length; while ((length = inputStream.read(b)) > 0) { os.write(b, 0, length); } // 这里主要关闭。 os.close(); inputStream.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // 返回值要注意,要不然就出现下面这句错误! //java+getOutputStream() has already been called for this response return null; }
参考文章:http://blog.ncmem.com/wordpress/2023/11/26/javaweb%e9%a1%b9%e7%9b%ae%e4%b8%ad%e7%9a%84%e6%96%87%e4%bb%b6%e4%b8%8a%e4%bc%a0%e4%b8%8b%e8%bd%bd%e5%8a%9f%e8%83%bd%e7%9a%84%e5%ae%9e%e7%8e%b0/
欢迎入群一起讨论