主要是利用 apache的 fileUpload...
首先要先設定前一頁submit的form型態為multipart, 而且只能使用POST method
< form name="b4page" id="b4page_info" method="POST" enctype="multipart/form-data" >
再來是submit下一頁後的jsp, 用fileUpload寫檔到server端的某一位置
<%@page import="org.apache.commons.io.*, org.apache.commons.fileupload.*, org.apache.commons.fileupload.disk.*, org.apache.commons.fileupload.servlet.*, java.io.*, java.util.*"%>
//upload file
boolean isUpload = false;
String foldar = "../tempImg/";
int MaxMemorySize = 1024*1024*100;
int limitFileSize = 5;
ServletFileUpload upload = null;
try {
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
// Set factory constraints
factory.setSizeThreshold(MaxMemorySize);
// Create a new file upload handler
upload = new ServletFileUpload(factory);
} catch(Exception e) { }
if(upload != null && upload.isMultipartContent(request)) {
isUpload = true;
}
if(isUpload) {
String key = (String)session.getAttribute("pic_key");
if(key == null) {
session.setAttribute("pic_key", String.valueOf(System.currentTimeMillis()));
key = (String)session.getAttribute("pic_key");
}
try {
// Parse the request
List items = upload.parseRequest(request);
Iterator iter = items.iterator();
FileItem imgFile = null;
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
//System.out.println("??item name="+item.getFieldName()+", "+item.isFormField());
if (item.isFormField()) { //此處取得的就是一般正常的param(text, hidden, select ...etc)
String fieldName = item.getFieldName();
String value = item.getString("UTF-8");
} else {
imgFile = item;
}
}
if(imgFile != null) {
String fieldName = imgFile.getFieldName();
String fileName = imgFile.getName();
String contentType = imgFile.getContentType();
boolean isInMemory = imgFile.isInMemory();
long sizeInBytes = imgFile.getSize();
if(sizeInBytes>1024*1024*limitFileSize) {
errMsg = "圖檔檔案過大(限制"+limitFileSize+" MB.), 請回上一頁重新上傳!!";
}
if(sizeInBytes>0){
String fname = key+fileName.substring(fileName.lastIndexOf("."));
// 先放在tmp裡!
File f = new File( foldar, fname );
//System.out.println("Upload File Path:"+f.getAbsolutePath());
imgFile.write(f);
//System.out.println("Upload File complete!");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
大概要比較注意的是, multipart傳上去的東西, getParameter這個method就get不到東西了...
要從isFormField那邊取得
沒有留言:
張貼留言