檔案上傳

放浪麴櫱發表於2020-11-06
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>My JSP 'uploat.jsp' starting page</title>
  </head>
  
  <body>
    <form action="${pageContext.request.contextPath}/servlet/UploadServlet3"  enctype="multipart/form-data" method="post">
           上傳使用者:<input type="text" name="username"><br/>
           上傳檔案:<input type="file" name="file1"><br/>
           上傳檔案:<input type="file" name="file2"><br/>
    <input type="submit" value="上傳">
    </form>
  </body>
</html>

UploadServlet2.java

package cn.xwy.web.servlet;


import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class UploadServlet2 extends HttpServlet {

	//處理上傳資料
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		try{
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setHeaderEncoding("UTF-8");


		List<FileItem> list = upload.parseRequest(request);
		for(FileItem item : list){
			if(item.isFormField()){
				//為普通輸入項
				String inputName = item.getFieldName();
				String inputValue = item.getString();
				System.out.println(inputName + "=" + inputValue);
			}else{
				//代表當前出來的item裡面分裝的是上傳檔案
				String filename = item.getName().substring(item.getName().lastIndexOf("\\")+1);
				InputStream in = item.getInputStream();
				int len = 0;
				byte buffer[] = new byte[1024];
				FileOutputStream out = new FileOutputStream("d:\\" + filename);
				while((len=in.read(buffer))>0){
					out.write(buffer,0,len);
				}
				in.close();
				out.close();
			}
		}
		}catch(Exception e){
			throw new RuntimeException(e);
		}
	}

	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doGet(request,response);
	}

}

//建立解析工廠

//建立解析器

//呼叫解析器解析request,得到儲存了所有上傳資料的list

//迭代list集合,拿到分裝了每個輸入項filename

//判斷item的型別,如果是普通欄位,則直接獲取資料,如果為上傳檔案,則呼叫留獲取資料寫到本地硬碟



相關文章