1. 程式人生 > >上傳檔案至伺服器Demo

上傳檔案至伺服器Demo

上傳檔案至伺服器,需要用到一個開源工具,file-upload.jar

在webcontent下建立一個新的資料夾upload

String uploadPath = getServletContext().getRealPath("upload");//上傳的檔案的儲存路徑

Servlet檔案

package main.web;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
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.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**上傳檔案至伺服器
 * Servlet implementation class FileUploadServlet
 */
@WebServlet("/FileUploadServlet")
public class FileUploadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    private String uploadPath = "";   
    /**
     * @see HttpServlet#HttpServlet()
     */
    public FileUploadServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    public void init(){
    	uploadPath = getServletContext().getRealPath("upload");
    	System.out.println(uploadPath);
    }
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("upload file....");
		request.setCharacterEncoding("UTF-8");
		// Check that we have a file upload request
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		if(!isMultipart){
			return;
		}
		//直接用getParameter()返回null
		//String filePath = request.getParameter("filepath");
		//System.out.println(filePath);
		
		// ①Create a factory for disk-based file items
		DiskFileItemFactory factory = new DiskFileItemFactory();

		// Configure a repository (to ensure a secure temp location is used)
		ServletContext servletContext = this.getServletConfig().getServletContext();
		File repository = (File) servletContext.getAttribute("filepath");
		factory.setRepository(repository);

		// ②Create a new file upload handler
		ServletFileUpload upload = new ServletFileUpload(factory);
		List<FileItem> items =null;
		// ③Parse the request,一個fileitem物件對應一個form表單域
		try {
			 items = upload.parseRequest(request);
		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//遍歷表單域
		for(FileItem item :items){
			if(item.isFormField()){//普通表單域
				String value = item.getString("UTF-8");
				String fieledName = item.getFieldName();//表單的name屬性
				System.out.println(value+" "+fieledName);
			}else{//上傳檔案域
				String value = item.getName();				
				String fieledName = item.getFieldName();//表單name屬性
				System.out.println(value+" "+fieledName);
				try {
					item.write(new File(uploadPath+File.separator+item.getName()));
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
		}
	}

}

jsp檔案
<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
	<form action="fileupload" method="post" enctype="multipart/form-data">
		使用者名稱:<input type="text" name="username"/>
		<input type="file" name="filepath"/>
		<input type="submit" value="上傳">
	</form>
</body>
</html>