大家会发现,enctype="multipart/form-data"的表单提交后,在后台无法用传统的request.getParameter获取其他参数
我个人理解是因为每个参数都用流的形式处理了,需要特别的方式才能获取
本文使用commons-fileupload 获取除file外其他参数
HTML代码:
< form id ="uploadFileForm" action ="UploadServlet" target ="hiddenFrame" method ="post" enctype ="multipart/form-data" >
< input id ="fileInput" type ="file" onchange ="uploadFile();" name ="upload" >
< input type ="hidden" value ="/image/" name ="directory" >
</ form >
Servlet代码:
package UI.FileManage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
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 UploadServlet extends HttpServlet {
@SuppressWarnings( " unchecked " )
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType( " text/html;charset=UTF-8 " );
String errorMessage = null ;
try {
DiskFileItemFactory fac = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(fac);
upload.setHeaderEncoding( " utf-8 " );
List fileList = null ;
fileList = upload.parseRequest(request);
String dir = ((FileItem)fileList.get( 1 )).getString(); // 获取directory参数
if (dir == null ) {
dir = " / " ;
}
String savePath = getServletContext().getRealPath( " /test " + dir);
System.out.println( " save at: " + savePath);
File f1 = new File(savePath);
if ( ! f1.exists()) {
f1.mkdirs();
}
Iterator < FileItem > it = fileList.iterator();
String name = "" ;
while (it.hasNext()) {
FileItem item = it.next();
if ( ! item.isFormField()) {
name = item.getName();
File file = new File(savePath + File.separatorChar + name);
if (file.exists()) {
errorMessage = " 该文件已经存在!请重命名后再上传。 " ;
}
item.write(file);
item.delete(); // 释放输出流
}
}
if (errorMessage == null ) {
response.getWriter().print( " <script> parent.finishUploading(1);</script> " );
} else {
response.getWriter().print( " <script> parent.finishUploading(0,' " + errorMessage + " ');</script> " );
}
} catch (Exception exception) {
response.getWriter().print( " <script> parent.finishUploading(0,'上传失败,请重试。');</script> " );
}
}
}