这篇文章主要介绍了Java结合WebUploader实现文件上传功能,代码简单易懂,非常不错,具有参考借鉴价值,需要的朋友可以参考下
之前自己写小项目的时候也碰到过文件上传的问题,没有找到很好的解决方案。虽然之前网找各种解决方案的时候也看到过WebUploader,但没有进一步深究。这次稍微深入了解了些,这里也做个小结。
简单的文件和普通数据上传并保存
jsp页面:
pageEncoding="UTF-8"%>
Insert title here文件:
信息:
servlet:package com.yihengliu.web.action;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
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;
import org.apache.commons.io.FileUtils;
/**
* Servlet user to accept file upload
*/
public class FileUploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private String serverPath = "e:/";
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.getWriter().append("Served at: ").append(request.getContextPath());
System.out.println("进入后台...");
// 1.创建DiskFileItemFactory对象,配置缓存用
DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
// 2. 创建 ServletFileUpload对象
ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
// 3. 设置文件名称编码
servletFileUpload.setHeaderEncoding("utf-8");
// 4. 开始解析文件
try {
List items = servletFileUpload.parseRequest(request);
for (FileItem fileItem : items) {
if (fileItem.isFormField()) { // >> 普通数据
String info = fileItem.getString("utf-8");
System.out.println("info:" + info);
} else { // >> 文件
// 1. 获取文件名称
String name = fileItem.getName();
// 2. 获取文件的实际内容
InputStream is = fileItem.getInputStream();
// 3. 保存文件
FileUtils.copyInputStreamToFile(is, new File(serverPath + "/" + name));
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
使用WebUploader组件上传
分片、并发,预览、压缩,多途径添加文件夹(文件多选,拖拽等),妙传
页面样式使用
使用webuploader上传文件上传
var uploader = WebUploader.create(
{
swf:"${pageContext.request.contextPath }/js/Uploader.swf",
server:"${pageContext.request.contextPath }/FileUploadServlet",
pick:"#filePicker",
auto:true
}
);