一、文件上传下载
-
文件上传
文件上传涉及到前台页面的编写和后台服务器端代码的编写,前台发送文件,后台接收 并保存文件,这才是一个完整的文件上传。
- 前台页面
在做文件上传的时候,会有一个上传文件的界面,首先我们需要一个表单,并且表单的 请求方式为 POST;其次我们的 form 表单的 enctype 必须设为 ”multipart/form-data” 即 enctype=“multipart/form-data” 意 思 是 设 置 表 单 的MIME 编码。默认情况下这个编码格式 是 ”application/x-www-form-urlencoded”, 不能用于文件上传;只有使用了 multipart/form-data 才能完整地传递文件数据。
<body> <!-- 文件上传 1、表单的提交类型为POST 2、表单类型设置为enctype="multipart/form-data" 3、表单元素需要设置name属性值 --> <form action="uploadServlet" method="POST" enctype="multipart/form-data" > 姓名:<input type="text" name="uname" /> 头像:<input type="file" name="myfile" /> <button>上传</button> </form> </body> </html>
- 后台 commons-fileupload 的使用
首先需要导入第三方 jar 包,http://commons.apache.org/ 下 载commons-io 和 commons-fileupload 两个 jar 的资源。解压并导入到项目中。commons-fileupload.jar 是文件上传的核心包 commons-io.jar 是 filefupload 的依赖包,同时又是一个工具包。
DiskFileItemFactory – 设置磁盘空间,保存临时文件。只是一个工具类
ServletFileUpload – 文件上传的核心类,此类接收 request,并解析
ServletFileUpload.parseRequest(request); – List 解析 requestpublic class UploadSource extends HttpServlet { protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 设定编码,可以获取中文文件名 req.setCharacterEncoding("UTF-8"); // 获取tomcat下的upload目录的路径 String path = getServletContext().getRealPath("/upload"); // 临时文件目录 String tempPath = getServletContext().getRealPath("/temp"); // 检查我们是否有文件上传请求 // boolean isMultipart = ServletFileUpload.isMultipartContent(req); // 1、声明DiskFileItemFactory工厂类,用于在指定磁盘上设置一个临时目录 DiskFileItemFactory disk = new DiskFileItemFactory(1024 * 10, newFile(tempPath)); // 2、声明ServletFileUpload,接收上面的临时文件。也可以默认值 ServletFileUpload up = new ServletFileUpload(disk); // 3、解析request try { List<FileItem> list = up.parseRequest(req); if (list.size() > 0) { for (FileItem file : list) // 判断是否是普通的表单项 if (file.isFormField()) { String fieldName = file.getFieldName(); // 中文乱码,此时还需要指定获取数据的编码方式 // String value = file.getString(); String value = file.getString("UTF-8"); System.out.println(fieldName + "=" + value); } else { // 说明是一个文件 // 获取文件本身的名称 String fileName = file.getName(); System.out.println(file.getFieldName()); // 处理文件名称 fileName = fileName.substring(fileName.lastIndexOf("\\") + 1); System.out.println("old Name : " + fileName); // 修改名称 String extName = fileName.substring(fileName.lastIndexOf(".")); String newName = UUID.randomUUID().toString().replace("-", "") + extName; // 保存新的名称,并写出到新文件中 file.write(new File(path + "/" + newName)); System.out.println("文件名是:" + fileName); System.out.println("文件大小是:" + file.getSize()); file.delete(); } } } catch (FileUploadException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } }
-
文件下载
- 超链接下载
当我们在 HTML 或 JSP 页面中使用标签时,原意是希望能够进行跳转,但当超链接遇到浏览器不识别的动态网页时则会自动下载。例如超链接下载但当遇见浏览器能够直接显示的资源,浏览器就会默认显示出来,比如 txt,png,jpg 等。当然我们也可以通过 download 属性规定浏览器进行下载。但有些浏览器并不支持。
a. 默认下载 (超链接下载)
<!--浏览器遇到能够识别的资源,会直接显示;遇到不能识别的资源,会下载。--> <a href="jay.jpg">图片</a> <br/>
download属性
<!--a标签设置download属性值后,点击a标签会执行下载。--> <a href="jay.jpg" download>图片</a> <br/> <!--download属性不设置属性值时,默认的下载名为文件名;若设置了属性值,则下载名与设置的属性值一致。--> <a href="upload.html" download="a.html">HTML页面</a>
- 后台实现下载
Step1:需要通过 HttpServletResponse.setContentType 方法设置 Content-type 头字段的值,为浏览器无法使用某种方式或激活某个程序来处理的 MIME 类型,
例 如 ”application/octet-stream” 或 ”application/x-msdownload” 等
Step2:需要通过 HttpServletResponse.setHeader 方法设置Content-Disposition 头的值为”attachment;filename=文件名”
Step3: 读取下载文件,调用 HttpServletResponse.getOutputStream 方法返回的 OutputStream 对象来向客户端写入附件内容。public class DownloadServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("UTF-8"); // 获取文件下载路径 String path = getServletContext().getRealPath("/") + "download/"; String fileName = req.getParameter("filename"); File file = new File(path + fileName); if (file.exists()) { // 设置相应类型 application/octet-stream resp.setContentType("application/x-msdownload"); // 设置头信息 resp.setHeader("Content-Disposition", "attachment;filename=" + fileName); InputStream is = new FileInputStream(file); ServletOutputStream os = resp.getOutputStream(); byte[] car = new byte[1024]; int len = 0; while ((len = is.read(car)) != -1) { os.write(car, 0, len); } // 关闭流、释放资源 os.close(); is.close(); } else { System.out.println("文件不存在,下载失败!"); } } }