- public class Uploadfile1 extends HttpServlet {
- @Override
- public void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- request.setCharacterEncoding("utf-8");
- //獲得磁盤檔案條目工廠。
- DiskFileItemFactory factory = new DiskFileItemFactory();
- //擷取檔案上傳需要儲存的路徑,upload檔案夾需存在。
- String path = request.getSession().getServletContext().getRealPath("/upload");
- //設定暫時存放檔案的存儲室,這個存儲室可以和最終存儲檔案的檔案夾不同。因為當檔案很大的話會占用過多記憶體是以設定存儲室。
- factory.setRepository(new File(path));
- //設定緩存的大小,當上傳檔案的容量超過緩存時,就放到暫時存儲室。
- factory.setSizeThreshold(1024*1024);
- //上傳處理工具類(高水準API上傳處理?)
- ServletFileUpload upload = new ServletFileUpload(factory);
- try{
- //調用 parseRequest(request)方法 獲得上傳檔案 FileItem 的集合list 可實作多檔案上傳。
- List<FileItem> list = (List<FileItem>)upload.parseRequest(request);
- for(FileItem item:list){
- //擷取表單屬性名字。
- String name = item.getFieldName();
- //如果擷取的表單資訊是普通的文本資訊。即通過頁面表單形式傳遞來的字元串。
- if(item.isFormField()){
- //擷取使用者具體輸入的字元串,
- String value = item.getString();
- request.setAttribute(name, value);
- }
- //如果傳入的是非簡單字元串,而是圖檔,音頻,視訊等二進制檔案。
- else{
- //擷取路徑名
- String value = item.getName();
- //取到最後一個反斜杠。
- int start = value.lastIndexOf("\\");
- //截取上傳檔案的 字元串名字。+1是去掉反斜杠。
- String filename = value.substring(start+1);
- request.setAttribute(name, filename);
- //收到寫到接收的檔案中。
- OutputStream out = new FileOutputStream(new File(path,filename));
- InputStream in = item.getInputStream();
- int length = 0;
- byte[] buf = new byte[1024];
- System.out.println("擷取檔案總量的容量:"+ item.getSize());
- while((length = in.read(buf))!=-1){
- out.write(buf,0,length);
- }
- in.close();
- out.close();
- }
- }
- }catch(Exception e){
- e.printStackTrace();
- }
- }
- }