这个功能要用到一个java开元的一个jar包
用SmartUpload类做上传
//初始化上传组件
su.initialize(config, request, response);
//设置上传文件的大小
//su.setMaxFileSize(1024*10*2);
//设置上传文件的总大小
//su.setTotalMaxFileSize(1024*10*10);
//设置上传文件的类型
su.setAllowedFilesList("jpg,bmp");
类如下:
package com.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.jspsmart.upload.File;
import com.jspsmart.upload.Files;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;
public class UploadServlet extends HttpServlet {
private ServletConfig config;
/**
* Constructor of the object.
*/
public UploadServlet() {
super();
}
@Override
public void init(ServletConfig config) throws ServletException {
// TODO Auto-generated method stub
this.config = config;
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request,response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=gbk");
PrintWriter out = response.getWriter();
SmartUpload su = new SmartUpload();
//初始化上传组件
su.initialize(config, request, response);
//设置上传文件的大小
//su.setMaxFileSize(1024*10*2);
//设置上传文件的总大小
//su.setTotalMaxFileSize(1024*10*10);
//设置上传文件的类型
su.setAllowedFilesList("jpg,bmp");
int count = 0;
try {
su.upload();
count = su.save("/upload");
Files files = su.getFiles();
out.println("<table border='1'>");
out.println("<tr>");
out.println("<th>filename</th>");
out.println("<th>ext</th>");
out.println("<th>img</th>");
out.println("</tr>");
for(int i=0;i<files.getCount();i++){
File file = files.getFile(i);
out.println("<tr>");
out.println("<td>"+file.getFileName()+"</td>");
out.println("<td>"+file.getFileExt()+"</td>");
out.println("<td><img src='"+request.getContextPath()+"/upload/"+file.getFileName()+"'>"+"</td>");
out.println("</tr>");
}
out.println("</table>");
} catch (SmartUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
out.println(count+"个文件上传成功!");
}
}
在jsp中用下面的方法获得文件路径
<form action="servlet/UploadServlet" method="post" enctype="multipart/form-data">
一定要写上
file1:<input type="file" name="filepath1"/><br>
file1:<input type="file" name="filepath2"/><br>
file1:<input type="file" name="filepath3"/><br>
file1:<input type="file" name="filepath4"/><br>
<input type="submit" value="upload"/>
</form>