pom.xml 中先添加依赖
javax.servlet javax.servlet-api 3.1.0 provided
上传用的 JSP
<%@ page contentType="text/html" pageEncoding="UTF-8" language="java" %>File Upload Select a file:
创建 Servlet 类
package com.seliote;import javax.servlet.ServletException;import javax.servlet.http.Part;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InputStream;public class FileUploadServlet extends javax.servlet.http.HttpServlet { protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws ServletException, IOException { // Get Part Part part = request.getPart("userFile"); if (part == null) { // Log it return; } // Read file InputStream inputStream = part.getInputStream(); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int readLength = -1; while ((readLength = inputStream.read(buffer)) != -1) { byteArrayOutputStream.write(buffer, 0, readLength); } response.getWriter().println("file length: " + byteArrayOutputStream.size()); byteArrayOutputStream.close(); } protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws ServletException, IOException { request.getRequestDispatcher("/index.jsp").forward(request, response); }}
修改部署描述符 web.xml
FileUploadServlet com.seliote.FileUploadServlet /tmp 20971520 41943040 5242880 FileUploadServlet /upload