利用getReader()和getInputstream()上传
package control; import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*; @WebServlet("/fileupload")
public class Fileupload extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//request.setCharacterEncoding("utf-8");
//方法一
/* ServletInputStream sis=request.getInputStream();
byte[] tmp=new byte[8192];
File file=new File("E:\\dc.zip");
FileOutputStream fos=new FileOutputStream(file);
int i=sis.read(tmp);
while (i!=-1){
fos.write(tmp,0,i);
i=sis.read(tmp);
}
fos.close();*/
//方法二
BufferedReader br=request.getReader();
/*File file=new File("E:\\da.doc");
BufferedWriter bw=new BufferedWriter(new FileWriter(file));*/
String s=br.readLine();
while (s!=null){
System.out.println(s);
s=br.readLine();
}
br.close();
PrintWriter out=response.getWriter();
out.write("success");
out.close();
} protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { }
}
Servlet3.0中Part,getPart()文件上传
package control; 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 java.io.IOException;
@MultipartConfig(location = "e:\\",maxFileSize = 1024*1024*2)//保存文件路径
@WebServlet("/ServletFile")
public class ServletFile extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
Part part=request.getPart("file");
String head=part.getHeader("Content-Disposition");//获取文件头Content-Disposition
System.out.println(head);
//获取文件名
int start=head.lastIndexOf("=\"");
String filename=head.substring(start+2);
filename=filename.substring(0,filename.length()-1);
System.out.println(filename);
part.write(filename);
} protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { }
}
多文件上传getParts()就是把单文件用foreach()处理
//多文档上传
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
for (Part part:request.getParts()){
String head=part.getHeader("Content-Disposition");//获取文件头Content-Disposition
System.out.println(head);
//获取文件名
int start=head.lastIndexOf("=\"");
String filename=head.substring(start+);
filename=filename.substring(,filename.length()-);
System.out.println(filename);
part.write(filename);