JavaWeb中的文件的上传和下载
作者:Neo丶
文件上传
1.要有一个form标签,method=post请求
2.form标签的encType属性的值必须为multipart/form-data值
3.在from标签中使用input type=file添加上传的文件
4.编写服务器代码接收上传的数据
Content-Type:表示提交的数据类型
enctype="multipart/form-data":表示提交的数据,以多段(每一个表单一个数据段)的形式进行拼接,然后以二进制流的形式发送给服务器
boundary:表示每段数据的分隔符
----WebKitFormBoundaryOZ1BoZwqflbGWUBH是由浏览器每次都随机生成,他就是每段数据的分界符
package com.pero.file.file_upload; import jakarta.servlet.*; import jakarta.servlet.http.*; import java.io.IOException; public class UploadServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("文件上传"); } }
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="https://jakarta.ee/xml/ns/jakartaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd" version="5.0"> <servlet> <servlet-name>UploadServlet</servlet-name> <servlet-class>com.pero.file.file_upload.UploadServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>UploadServlet</servlet-name> <url-pattern>/uploadServlet</url-pattern> </servlet-mapping> </web-app>
<%-- Created by IntelliJ IDEA. User: Administrator Date: 2023/3/15 Time: 23:08 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <form action="http://localhost:8080/file_Upload/uploadServlet" method="post" enctype="multipart/form-data"> 用户名:<input type="text" name="username"/> 头像:<input type="file" name="photo"/> <input type="submit" value="上传"> </form> </body> </html>
常用API
导入commons-fileupload-1.3.3.jar和commons-io-2.6.jar包到项目lib目录下
常用类:
- ServletFileUpload类:用于解析上传的数据
- FileItem类:表示每一个表单项
- boolean ServletFileUpload.isMultipartContent(HttpServletRequest request):判断当前上传的数据格式是否为多段的格式
- public List<FileItem> parseRequest(HttpServletRequest request):解析上传数据
- boolean isFormField():判断当前表单项是普通表单项还是上传的文件类型,true表示表单项,false表示上传的文件类型
- String getFieldName():获取表单项的name属性值
- String getString():获取当前表单项的值
- String getName():获取上传的文件名
- void write(File var1) throws Exception:将上传的文件写到参数file所指向的硬盘位置
文件上传测试
package com.pero.servlet; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileItemFactory; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.IOException; import java.util.List; public class UploadServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("UTF-8"); //先判断上传数据是否为多段数据(只有多段数据才是文件上传的) if (ServletFileUpload.isMultipartContent(req)) { //创建FileItemFactory工厂实现类 FileItemFactory fileItemFactory = new DiskFileItemFactory(); //创建用于解析上传数据的工具类 ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory); //解析上传的数据得到每一个表单项Item try { List<FileItem> list = servletFileUpload.parseRequest(req); //循环判断每一个表单项是普通类型还是上传文件 for (FileItem fileItem : list) { if (fileItem.isFormField()) { //普通表单项 System.out.println("表单项的name属性值:" + fileItem.getFieldName()); //参数UTF-8解决中文乱码 System.out.println("表单项的value值:" + fileItem.getString("UTF-8")); } else { //上传文件 System.out.println("表单项的name属性值:" + fileItem.getFieldName()); System.out.println("上传文件名:" + fileItem.getName()); fileItem.write(new File("G:\\test" + fileItem.getName())); } } } catch (Exception e) { throw new RuntimeException(e); } } } }
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="https://jakarta.ee/xml/ns/jakartaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_6_0.xsd" version="6.0"> <servlet> <servlet-name>UploadServlet</servlet-name> <servlet-class>com.pero.servlet.UploadServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>UploadServlet</servlet-name> <url-pattern>/uploadServlet</url-pattern> </servlet-mapping> </web-app>
<%-- Created by IntelliJ IDEA. User: Administrator Date: 2023/3/15 Time: 23:08 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <form action="http://192.168.42.31:8080/Upload_Web/uploadServlet" method="post" enctype="multipart/form-data"> 用户名:<input type="text" name="username"/><br> 头像:<input type="file" name="photo"/><br> <input type="submit" value="上传"> </form> </body> </html>
文件的下载
客户端发送请求告诉服务器需要下载什么文件,服务器过去要下载的文件名,读取要下载的文件内容,把下载的文件内容回传给客户端,再回传前,通过响应头告诉客户端返回的数据类型,还要通过响应头告诉客户端收到的数据是用于下载使用
常用API说明:
- response.getOutputStream():获取响应输出流
- servletContext.getResourceAsStream():用于读取要下载的内容(返回对象为输入流)
- servletCOntext.getMimeType():获取要下载的文件类型
- response.setContentType():在回传之前通过响应头告诉客户端返回的数据类型
response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode("你好.png","UTF-8"));该响应头是告诉浏览器,这个文件是要下载的文件。attachment表示附件,也就是下载的文件,fileName=后面的表示下载的文件名
package com.pero.servlet.download_web; import jakarta.servlet.*; import jakarta.servlet.http.*; import org.apache.commons.io.IOUtils; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URLEncoder; public class Download extends HttpServlet { @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1.获取要下载的文件名 String downloadFileName = "1.png"; //2.读取要下载的文件内容(通过ServletContext对象读取) ServletContext servletContext = getServletContext(); //获取要下载的文件类型 String mimeType = servletContext.getMimeType("/file/" + downloadFileName); System.out.println("下载的文件类型:" + mimeType); //再回传之前通过响应头告诉客户端返回的数据类型 response.setContentType(mimeType); //还要告诉客户端收到的数据是用于下载使用(还是使用响应头) //Content-Disposition响应头表示收到的数据怎么处理 //attachment表示指定下载的文件名 //url编码是把汉字转换成%xx%xx的格式 response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode("你好.png","UTF-8")); InputStream resourceAsStream = servletContext.getResourceAsStream("/file/" + downloadFileName); //获取响应输出流 OutputStream outputStream = response.getOutputStream(); //把要下载的文件内容回传给客户端 //读取输入流中全部的数据赋值给输出流,输出给客户端 IOUtils.copy(resourceAsStream, outputStream); } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="https://jakarta.ee/xml/ns/jakartaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd" version="5.0"> <servlet> <servlet-name>Download</servlet-name> <servlet-class>com.pero.servlet.download_web.Download</servlet-class> </servlet> <servlet-mapping> <servlet-name>Download</servlet-name> <url-pattern>/download</url-pattern> </servlet-mapping> </web-app>
到此这篇关于JavaWeb中的文件的上传和下载的文章就介绍到这了,更多相关JavaWeb文件上传下载内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!