Servlet3.0 提供了专门的文件上传 API。
HttpServletRequest 的 getPart()方法可以完成单个文件上传,而 getParts()方法可以完成多个文件上传。注意,这两个方法是从 Servlet3.0 开始定义的。
getPart
方法:Part getPart(String name) throws IOException, ServletException
作用:获取 Multipart 请求中指定名称的”部分”。一般这里的参数是上传表单中的”file”表单项的 name 值。
getParts
方法:java.util.Collection getParts()throws IOException, ServletException
作用:获取 Multipart 请求中的所有”部分”。多文件上传时使用该方法。
Servlet3.0在javax.servlet.http包中新增了Part接口,该接口中常用的方法有:
write
方法:void write(String fileName) throws IOException
作用:将上传文件数据写入到指定的文件中。
另外在Servlet3.1中的Part接口里面新增了getSubmittedFileName方法用来获取上传的文件名
所以我们直接用3.1 反正你喜欢..
还有就是一个:@MultipartConfig // @MultipartConfig 表示当前servlet可以处理multipart请求 这个加载Servlet,加上吧 .... 复制即可
所以我们直接干就完了:
package upload;
import java.io.IOException;
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("/upload")
@MultipartConfig // @MultipartConfig 表示当前servlet可以处理multipart请求 这个加上吧
public class upload extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Part part = request.getPart("img"); //Part 通过request 获取, 参数是文件域的name
String path = this.getServletContext().getRealPath("/img");
String FileName = part.getSubmittedFileName(); //Servlet3.1才有的!!!
//写出到内个img文件夹中
part.write(path + "/" + FileName); //别粗心!!! 记得 + 斜杠
System.out.println(path);
System.out.println(FileName);
}
}
自己看吧 我累了 拜拜.