jave web 批量上传
我的需求是这样的:Servlet+JSP 进行开发 只有一个<input type="file"/>,可以选择多个文件上传,服务器端接收这些文件,将它们的路径保存到数据库中。我在网上看了很多,要用到swfupload组件,可是我不会用这个组件(老外写的,看不懂)。请高手给指点一下,如果代码太多,可以发到我的邮箱里:jianghaodongok@yahoo.cn 如能解决问题,不胜感激。
[最优解释]
<script type="text/javascript" language="javascript">
var uploaderMgr = new HttpUploaderMgr();
uploaderMgr.Load();//加载控件
window.onload = function()
{
uploaderMgr.Init();//初始化控件
//添加一个本地文件
uploaderMgr.AddFile("D:\\Soft\\QQ2010.exe");
uploaderMgr.PostFirst();
};
</script>
服务器返回消息:<input id="txtFilePath" type="text" size="50" />
<script type="text/javascript" language="javascript">
var uploaderMgr = new HttpUploaderSingleMgr();
uploaderMgr.Config["PostUrl"] = "http://localhost:8080/asp.net/upload.aspx";
uploaderMgr.Load();
//文件上传完成后执行的回调函数
uploaderMgr.CompleteHook = function(msg)
{
document.getElementById("txtFilePath").value = msg;
};
window.onload = function()
{
uploaderMgr.Init();
};
</script>
import java.io.File;
import java.io.IOException;
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.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import com.bjcq.tool.Tool;
public class FileUploadServlet extends HttpServlet {
private static final long serialVersionUID = -7825355637448948879L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request,response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
uploadFile(request,response);
}
private void uploadFile(HttpServletRequest request, HttpServletResponse response){
String dir = request.getSession().getServletContext().getRealPath("/uploadFile");//把上传的文件保存在uploadFile文件夹里
File file = new File(dir);
if(!file.exists())
file.mkdirs();
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
//防止中文文件名乱码
upload.setHeaderEncoding("UTF-8");
try {
List<FileItem> items = upload.parseRequest(request);
if (items != null) {
Iterator<FileItem> itr = items.iterator();
while (itr.hasNext()) {
FileItem item = (FileItem) itr.next();
if (item.isFormField()) {
continue;
} else {
File savedFile=new File(dir+File.separator+item.getName());
item.write(savedFile);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
try {
response.getOutputStream().println("200 OK");
} catch (IOException e) {
e.printStackTrace();
}
}
}