上傳檔案並目錄打散

久夢歌行發表於2014-12-05

上傳表單

<form action="${pageContext.request.contextPath }/Upload3" method="post" enctype="multipart/form-data">
  使用者名稱;<input type="text" name="username"/><br/>
  照 片:<input type="file" name="zhaoPian"/><br/>
  <input type="submit" value="上傳"/>
</form>

servlet程式碼

package web.servlet;

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

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

/**
 * 目錄打散練習
 * @author zhaozhihang
 *
 */
public class Upload3 extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 三部曲
		DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
		ServletFileUpload sfu = new ServletFileUpload(diskFileItemFactory);
		try {
			List<FileItem> list = sfu.parseRequest(request);
			FileItem f = list.get(1);
//			String s = request.getSession().getServletContext().getRealPath("/WEB-INF/files");
			//得到檔案的儲存路徑
			String root = this.getServletContext().getRealPath("/WEB-INF/files");
			/*
			 * 1 得到檔名稱
			 * 2 裝換成hashCode
			 */
			String filename = f.getName();
			//判斷是否有斜槓
			int index = filename.lastIndexOf("\\");
			if(index!=-1) {
				filename = filename.substring(index+1);
			}
			
			String savename = UUID.randomUUID().toString().replace("-", "")+filename;
			
			//得到hashCode
			int hCode = filename.hashCode();
			String hex = Integer.toHexString(hCode);
			File file = new File(root, hex.charAt(0)+"/"+hex.charAt(1)); 
			
			//建立目錄鏈
			file.mkdirs();
			
			//建立目標檔案
			File destFile = new File(file, savename);
			
			f.write(destFile);
		} catch (FileUploadException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}


相關文章