html页面代码:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>上传文件</title> </head> <body> <form action="upload" enctype="multipart/form-data" method="post"> 文件名:<input type="text" id="name" name="name"/><br/> 选择文件:<input type="file" id="file" name="file"/><br/> <input type="submit" value="上传"/> </form> </body> </html>
java端代码:
package com.lee.upload; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.Collection; 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; @WebServlet(name="upload",urlPatterns="/upload") @MultipartConfig public class UploadServlet extends HttpServlet { @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html;charset=UTF-8"); PrintWriter out=resp.getWriter(); String filename=req.getParameter("name"); Part part=req.getPart("file"); out.println("上传的文件类型为"+part.getContentType()+"<br/>"); out.println("上传的文件大小为:"+part.getSize()); Collection<String> headerNames=part.getHeaderNames(); for (String headname : headerNames) { out.println(headname+"--->"+part.getHeader(headname)+"<br/>"); } File f=new File(getServletContext().getRealPath("/uploadFiles")); f.mkdir(); part.write(getServletContext().getRealPath("/uploadFiles")+"/"+filename); } }