依赖jar
<dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.4</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> <scope>provided</scope> </dependency>
示例如下:
1. 新建Maven项目 upload
war 类型
2. pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.java</groupId> <artifactId>upload</artifactId> <version>1.0.0</version> <packaging>war</packaging> <dependencies> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.4</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> <scope>provided</scope> </dependency> </dependencies> <build> <finalName>${project.artifactId}</finalName> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.8</source> <target>1.8</target> <encoding>UTF-8</encoding> </configuration> </plugin> </plugins> </build> </project>
3. UploadFileServlet.java
package com.java.servlet; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.ServletException; 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.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.io.FileUtils; /** * 原生Servlet上传文件 * */ public class UploadFileServlet extends HttpServlet { private static final long serialVersionUID = -755404037178760784L; /** * 设置字符集为UTF-8 */ private static final String ENCODING = "UTF-8"; @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (ServletFileUpload.isMultipartContent(request)) { try { DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = upload.parseRequest(request); // 存储普通表单参数 Map<String, String> paramMap = new HashMap<>(); // 存储文件参数 Map<String, FileItem> fileMap = new HashMap<>(); /* 解析表单参数 */ for (FileItem item : items) { // 普通表单参数 if (item.isFormField()) { paramMap.put(item.getFieldName(), item.getString(ENCODING)); } // 文件参数 else { fileMap.put(item.getFieldName(), item); } } /* 从参数集合中获取需要的参数 */ String uploadPath = paramMap.get("uploadPath"); FileItem fileItem = fileMap.get("file"); String fileName = fileItem.getName(); File outFile = new File(uploadPath, fileName); if (outFile.exists()) { FileUtils.forceDelete(outFile); } fileItem.write(outFile); write(response, "上传完成:" + outFile.getAbsolutePath()); } catch (FileUploadException e) { e.printStackTrace(); write(response, e.getMessage()); } catch (Exception e) { e.printStackTrace(); write(response, e.getMessage()); } } // 请求Content-type设置错误时给出提示 else { write(response, "非multipart类型,检查Content-type"); } } private void write(HttpServletResponse response, String message) { response.setContentType("text/html; charset=UTF-8"); PrintWriter writer = null; try { writer = response.getWriter(); writer.write(message); writer.flush(); } catch (IOException e) { e.printStackTrace(); } finally { writer.close(); } } }
4. 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_2_5.xsd" version="2.5"> <display-name>upload</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>uploadFile</servlet-name> <servlet-class>com.java.servlet.UploadFileServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>uploadFile</servlet-name> <url-pattern>/uploadFile</url-pattern> </servlet-mapping> </web-app>
5. 新建页面文件 src/main/webapp/index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <!DOCTYPE html> <html> <head> <title>上传文件</title> <base href="<%=basePath%>"> <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> </head> <body> <form action="uploadFile" enctype="multipart/form-data" method="post"> <table> <tr> <th>选择上传文件:</th> <td><input name="file" type="file" /></td> </tr> <tr> <th>上传服务器路径:</th> <td><input name="uploadPath" type="text" placeholder="上传服务器路径" /></td> </tr> <tr> <td colspan="2"><button type="submit">上传</button></td> </tr> </table> </form> </body> </html>
部署到tomcat下,启动
浏览器输入 http://localhost:8080/upload/
如下所示:
选择文件,输入上传路径 G:TempTest 如下所示:
单击【上传】,返回信息如下:
上传完成:G:TempTestfastjson-1.2.49.jar
查看G:TempTest,文件已上传成功!
.