Servlet:
import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import javax.servlet.ServletException; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.Part; import org.apache.tomcat.util.http.fileupload.IOUtils; @WebServlet(name = "FileUploadServlet", urlPatterns = {"/upload"}) @MultipartConfig public class DynamicInvoke extends HttpServlet { private static final long serialVersionUID = 1L; protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Part filePart = request.getPart("file"); try(InputStream inputStream = filePart.getInputStream();){ IOUtils.copy(inputStream, new FileOutputStream(String.format("D:/%s", request.getParameter("fileName")))); } response.getWriter().println("success"); } }
HTML:
<!DOCTYPE html> <html> <head> <title>File Upload</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> </head> <body> <form method="POST" action="upload" enctype="multipart/form-data" > File: <input type="file" name="file" id="file" /> <br/> FileName: <input type="text" value="temp.txt" name="fileName"/> <br> <input type="submit" value="Upload" name="upload" id="upload" /> </form> </body> </html>
原文:http://my.oschina.net/u/1756290/blog/523107