1. 程式人生 > >網站上傳檔案學習筆記

網站上傳檔案學習筆記


public class UpLoadServlet extends HttpServlet {
public UpLoadServlet() {
super();
}
public void destroy() {
super.destroy();
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//request.setCharacterEncoding("utf-8");
//檔案的快取工廠
String path=getServletContext().getRealPath("/WEB-INF/file");
String str=UUID.randomUUID().toString();
DiskFileItemFactory dff=new DiskFileItemFactory();
//設定臨時檔案
dff.setRepository(new File(path));
//開始建立request解析器
ServletFileUpload sfu=new ServletFileUpload(dff);
//設定檔案大小上限,單位
sfu.setFileSizeMax(1024*1024*1024);
//通過解析器解析request
try {
List<FileItem> list= sfu.parseRequest(request);
FileItem f1=list.get(0);
FileItem f2=list.get(1);
InputStream is=f2.getInputStream();
File file=new File(path+"/"+str+".mp4");
FileOutputStream fos=new FileOutputStream(file);
byte[] b=new byte[1024];
int len=-1;
while((len=is.read(b))!=-1){
fos.write(b);
fos.flush();
}
fos.close();
is.close();
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
public void init() throws ServletException {
}
}