本篇文章为大家展示了java中怎么利用servlet实现文件上传功能,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8" /><title>上传文件</title><link href="../css/bootstrap.min.css" rel="external nofollow" rel="stylesheet"><script src="../js/jquery.min.js"></script><script src="../js/bootstrap.min.js" type="text/javascript"></script></head><body> <p class="container kv-main"> <p class="page-header"> <h2>上传文件</h2> </p> <form enctype="multipart/form-data" action="../upload?method=uploadPic" method="post"> <input name="file-1" type="file"><br> <button type="submit" class="btn btn-primary">Submit</button> <button type="reset" class="btn btn-default">Reset</button> </form> <hr> <br> </p> </body></html>
这个地方是为了好看使用了Bootstrap进行布局,如下:
在做好前台的页面之后,我们开看后台的代码,在看servlet之前我们首先来看看web.xml的配置:
<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>myShop</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>upload</servlet-name> <servlet-class>com.epoint.shop.fileupload.UpLoadServlet</servlet-class> <init-param> <param-name>filePath</param-name> <param-value>E://workspace1/myShop/WebContent/upload</param-value> </init-param> <init-param> <param-name>tempFilePath</param-name> <param-value>temp</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>upload</servlet-name> <url-pattern>/upload</url-pattern> </servlet-mapping></web-app>
为什么要配置web.xml,是因为我们在servlet有一个要获取文件存放的路径,我们不妨将这个路径存放到web.xml这个我们当我们的项目进行平台的迁移的时候,我们需要改动的只是web.xml不需要给java内部的核心的代码。
然后我们来看servlet的代码:
package com.epoint.shop.fileupload; import java.io.File;import java.io.IOException; import java.io.PrintWriter;import java.lang.reflect.Method;import java.util.List; import javax.servlet.ServletConfig;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.commons.fileupload.FileItem;import org.apache.commons.fileupload.disk.DiskFileItemFactory;import org.apache.commons.fileupload.servlet.ServletFileUpload;@WebServlet("/UpLoad")public class UpLoadServlet extends HttpServlet { private static final long serialVersionUID = 1L; private static String TEMP_FOLDER="/upload"; // 上传配置 private static final int MEMORY_THRESHOLD = 1024 * 1024 * 3; // 3MB private static final int MAX_FILE_SIZE = 1024 * 1024 * 40; // 40MB private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50; // 50MB private String filePath; //存放上传文件的目录 private String tempFilePath; //存放临时文件的目录 public UpLoadServlet() { super(); } public void init(ServletConfig config)throws ServletException { super.init(config); filePath=config.getInitParameter("filePath"); System.out.println(filePath); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); String methodName=request.getParameter("method"); if(methodName!=null){ try { Method method=this.getClass().getDeclaredMethod(methodName,HttpServletRequest.class,HttpServletResponse.class); method.invoke(this, request,response); } catch (Exception e) { e.printStackTrace(); } } } public void uploadPic(HttpServletRequest request, HttpServletResponse response) throws Exception{ //检测是否为多媒体上传 if(!ServletFileUpload.isMultipartContent(request)){ //如果不是就停止 PrintWriter writer=response.getWriter(); writer.println("表单中必须包含enctype=multipart/form-data"); writer.flush(); return; } DiskFileItemFactory factory = new DiskFileItemFactory(); // 创建文件项目工厂对象 factory.setRepository(new File(savePath)); //设置临时文件夹为TEMP_FOLDER factory.setSizeThreshold(1024 * 1024); // 设置缓冲区大小为 1M // 构造临时路径来存储上传的文件 ServletFileUpload upload = new ServletFileUpload(factory);//用工厂实例化上传组件,ServletFileUpload用来解析文件上传请求 // 设置最大文件上传值 upload.setFileSizeMax(MAX_FILE_SIZE); // 设置最大请求值 (包含文件和表单数据) upload.setSizeMax(MAX_REQUEST_SIZE); upload.setHeaderEncoding("UTF-8"); @SuppressWarnings("unchecked") List<FileItem> list = upload.parseRequest(request); if (list != null && list.size() > 0) { for (FileItem item : list) { if (!item.isFormField()) { String fileName = new File(item.getName()).getName(); File storeFile = new File(filePath,fileName); // 保存文件到硬盘 item.write(storeFile); request.setAttribute("message","文件上传成功!"); } } } } }
在今天上午我在编写的过程中遇到一个问题,就是有一个
List<FileItem> list = upload.parseRequest(request);
就这个代码获取到的list一直为空,如果你也遇到这样的问题,可以配置一下web.xml,因为我们tomcat可能会对文件进行拦截,但是我也不清楚为什么在配置了web.xml之后,就可以上传文件了。你如果遇到这样的问题不妨是试一试,请求通过web.xml的mapping进行转发。
上述内容就是java中怎么利用servlet实现文件上传功能,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。