文件的上传与下载(一)
在实现文件上传和下载之前我们需要做一些准备工作,在Apache官网去下载文件上传下载的两个组件,下载链接这里给出:common-fileupload组件下载:http://commons.apache.org/proper/commons-fileupload/
common-io组件下载:http://commons.apache.org/proper/commons-io/根据自己需求下载对应版本
一、创建工程
将所需要的两个开发包导入到工程项目中如图:
二、代码编写
1.前端页面代码
1). 在WebRoot目录下新建一个fileUpload.jsp页面,用来上传文件
1 <%@ page language="java" import="java.util.*" pageEncoding="GB18030"%> 2 <% 3 String path = request.getContextPath(); 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 5 %> 6 7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 8 <html> 9 <head> 10 <base href="<%=basePath%>"> 11 12 <title>My JSP 'fileUpload.jsp' starting page</title> 13 14 <meta http-equiv="pragma" content="no-cache"> 15 <meta http-equiv="cache-control" content="no-cache"> 16 <meta http-equiv="expires" content="0"> 17 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 18 <meta http-equiv="description" content="This is my page"> 19 <!-- 20 <link rel="stylesheet" type="text/css" href="styles.css"> 21 --> 22 23 </head> 24 25 <body> 26 <!-- 文件上传表单的提交方式必须是“post” 编码类型必须为:enctype="multipart/form-data" --> 27 <form action="UploadServlet" method="post" enctype="multipart/form-data"> 28 29 username: <input type="text" name="username" /><br> 30 file: <input type="file" name="file"><br> 31 file2: <input type="file" name="file2"><br> 32 <input type="submit" value="上传文件"> 33 34 </form> 35 36 </body> 37 </html>
2). 新建一个fileUploadResult.jsp页面用来显示结果信息
1 <%@ page language="java" import="java.util.*,java.io.*" pageEncoding="GB18030"%> 2 <% 3 String path = request.getContextPath(); 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 5 %> 6 7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 8 <html> 9 <head> 10 <base href="<%=basePath%>"> 11 12 <title>My JSP 'fileUploadResult.jsp' starting page</title> 13 14 <meta http-equiv="pragma" content="no-cache"> 15 <meta http-equiv="cache-control" content="no-cache"> 16 <meta http-equiv="expires" content="0"> 17 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 18 <meta http-equiv="description" content="This is my page"> 19 <!-- 20 <link rel="stylesheet" type="text/css" href="styles.css"> 21 --> 22 23 </head> 24 25 <body> 26 <%-- 27 <% 28 //获取流对象 29 InputStream inputStream = request.getInputStream(); 30 31 BufferedReader br = new BufferedReader(new InputStreamReader(inputStream)); 32 33 String buffer = null; 34 35 while((buffer = br.readLine()) != null){ 36 out.print(buffer + "<br>"); 37 } 38 39 br.close(); 40 inputStream.close(); 41 42 %> 43 --%> 44 ${message}<br> 45 46 EL-username : ${requestScope.username} <br> 47 EL-file1 : ${requestScope.file }<br> 48 EL-file2 : ${requestScope.file2}<br> 49 50 </body> 51 </html>
2. 编写上传文件处理的Servlet代码
1) UploadServlet.java代码如下:
1 package com.Servlet; 2 3 import java.io.File; 4 import java.io.FileOutputStream; 5 import java.io.IOException; 6 import java.io.InputStream; 7 import java.io.PrintWriter; 8 import java.util.List; 9 10 import javax.servlet.ServletException; 11 import javax.servlet.http.HttpServlet; 12 import javax.servlet.http.HttpServletRequest; 13 import javax.servlet.http.HttpServletResponse; 14 15 import org.apache.commons.fileupload.FileItem; 16 import org.apache.commons.fileupload.disk.DiskFileItemFactory; 17 import org.apache.commons.fileupload.servlet.ServletFileUpload; 18 19 public class UploadServlet extends HttpServlet { 20 21 /** 22 * The doPost method of the servlet. <br> 23 * 24 * This method is called when a form has its tag value method equals to post. 25 * 26 * @param request the request send by the client to the server 27 * @param response the response send by the server to the client 28 * @throws ServletException if an error occurred 29 * @throws IOException if an error occurred 30 */ 31 public void doPost(HttpServletRequest request, HttpServletResponse response) 32 throws ServletException, IOException { 33 34 35 //得到上传文件的保存目录,将上传的文件放在webRoot目录下(但是一般为了安全放在WEB-INF目录下,不允许外界直接访问,保证上传的安全) 36 String path = this.getServletContext().getRealPath("/upload"); 37 38 File file = new File(path); 39 40 //判断上传文件的保存目录是否存在 41 if(!file.exists() && !file.isDirectory()){ 42 System.out.println(path + "目录不存在,需要创建!"); 43 //创建目录 44 file.mkdir(); 45 } 46 //消息提示 47 String message = ""; 48 try{ 49 //使用Apache文件上传组件处理文件上传步骤: 50 //1.创建一个DiskFileItemFactory工厂 51 DiskFileItemFactory factory = new DiskFileItemFactory(); 52 //2.创建一个文件上传解析器 53 ServletFileUpload upload = new ServletFileUpload(factory); 54 //解决中文乱码 55 upload.setHeaderEncoding("UTF-8"); 56 //3.判断提交的数据普通表单的数据还是带文件上传的表单 57 if(!upload.isMultipartContent(request)){ 58 //如果是表单数据普通表单,则按照传统方式获取数据 59 return ; 60 } 61 //4.使用ServletFileUpload解析器解析上传数据,解析结果返回的是一个List<FileItem>集合,每一个FileItem对应一个Form表单的输入项 62 List<FileItem> list = upload.parseRequest(request); 63 for(FileItem item : list){ 64 //如果fileItem中封装的是普通输入项的数据 65 if(item.isFormField()){ 66 //获取字段名字 67 String name = item.getFieldName(); 68 //解决普通输入项中中文乱码问题 69 String value = item.getString("UTF-8");//value = new String(value.getBytes("iso8859-1"),"UTF-8"); 70 System.out.println(name + " = " + value); 71 }else{ //如果表单中提交的是上传文件 72 //获得上传的文件名称 73 String filename = item.getName(); 74 System.out.println(filename); 75 if(filename == null || filename.trim().equals(" ")){ 76 continue; 77 } 78 //注意:不同的浏览器提交的文件名称是不一样的,有些浏览器提交的文件会带有路径,如“D:\\project\WebRoot\hello.jsp”,有一些是单纯的文件名:hello.jsp 79 //去掉获取到文件名中的路径名,保留单纯的文件名 80 filename = filename.substring(filename.lastIndexOf("\\") + 1); 81 //获取item中的上传文件的输入流 82 InputStream in = item.getInputStream(); 83 //创建一个文件输入流 84 FileOutputStream out = new FileOutputStream(path + "\\" + filename); 85 //创建一个缓冲区 86 byte buffer[] = new byte[1024]; 87 //判断输入流中的数据是否已经读取完毕的标志位 88 int len = 0; 89 //循环将输入流读入到缓冲区当中,(len = in.read(buffer)>0)就表示in里面还有数据存在 90 while((len = in.read(buffer)) > 0){ 91 //使用FileOutputStream输出流将缓冲区的数据写入到指定的目录(path+"\\"+filename)当中 92 out.write(buffer, 0, len); 93 } 94 //关闭输入流 95 in.close(); 96 //关闭输出流 97 out.close(); 98 //删除处理文件上传生成的临时文件 99 item.delete(); 100 message = "文件上传成功!"; 101 102 103 } 104 } 105 106 }catch(Exception e){ 107 message = "文件上传失败!"; 108 e.printStackTrace(); 109 } 110 111 request.setAttribute(message, message); 112 request.getRequestDispatcher("fileUploadResult.jsp").forward(request, response); 113 114 } 115 116 }
2)web.xml文件中的配置
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app version="3.0" 3 xmlns="http://java.sun.com/xml/ns/javaee" 4 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 5 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> 6 <servlet> 7 8 <servlet-name>UploadServlet</servlet-name> 9 <servlet-class>com.Servlet.UploadServlet</servlet-class> 10 </servlet> 11 12 <servlet-mapping> 13 <servlet-name>UploadServlet</servlet-name> 14 <url-pattern>/UploadServlet</url-pattern> 15 </servlet-mapping> 16 17 </web-app>
结果:
摘自:https://www.cnblogs.com/xdp-gacl/p/4200090.html
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步