bootstrap-fileinput实现serverlet文件上传功能

来源:互联网 发布:nba球员名字大全及数据 编辑:程序博客网 时间:2024/06/05 11:22
年底了,很忙,但接到一个档案系统的开发。于是开始搭框架,做界面,因为老板要求要漂亮些,于是使用了冷藏的bootstrap(IE6兼容性不好,之前老板不让用),应用bootstrap-fileinput的插件做文档上传,但是原有框架使用的servlet的文件上传方式,不符合bootstrap-fileinput的上传要求。没兴趣重新写后台了(主要是时间太紧)。改改能用就成!

看我混世大法


关于bootstrap-fileinput的介绍(中文版)
http://www.cnblogs.com/wuhuacong/p/4774396.html
里面有些地方注意下
1、initFileInput("file-Portrait", "/User/EditPortrait");=>initFileInput("file-Portrait1", "/User/EditPortrait");
2、如果要传递多个文件,请使用<input id="file-Portrait1" multiple type="file" />

后台部分完全抛弃,看点符合java开发AOP理念的代码

原权限管理框架代码来自孙宇大神的SSHE项目,就照着改了。

少废话,放狗(源代码)

PIUploadServlet.java(使用了org.apache commons-fileupload、commons-lang等jar包)

package sy.util.base;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

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.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;

import com.alibaba.fastjson.JSON;
import com.opensymphony.xwork2.util.logging.log4j2.Log4j2Logger;

public class PlUploadServlet extends HttpServlet {

public PlUploadServlet() {
super();
}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String fileFolder = request.getParameter("fileFolder");// 前台传递过来的文件夹参数,如果有就在这个目录里面保存文件
if (StringUtils.isBlank(fileFolder)) {
fileFolder = "/temp";// 避免前台没有传递这个参数的时候会报错
}
String datefolder = "/" + DateUtil.dateToString(new Date(), "yyyy") + "/" + DateUtil.dateToString(new Date(), "MM") + "/" + DateUtil.dateToString(new Date(), "dd");// 日期命名的文件夹
String webParentPath = new File(request.getSession().getServletContext().getRealPath("/")).getParent();// 当前WEB环境的上层目录
String realPath = webParentPath + ConfigUtil.get("uploadPath") + fileFolder + datefolder;// 文件上传到服务器的真实路径
// System.out.println(realPath);
String path = ConfigUtil.get("uploadPath") + fileFolder + datefolder;// 文件在服务器的相对路径
System.out.println("request.filename="+request.getParameter("filename"));
System.out.println("request.name="+request.getParameter("name"));
// System.out.println(path);
if (request.getSession() == null || request.getSession().getAttribute(ConfigUtil.getSessionInfoName()) == null) {// 如果用户没有登录,则不允许上传
Map<String, Object> m = new HashMap<String, Object>();
m.put("status", false);
response.getWriter().write(JSON.toJSONString(m));
} else {
File up = new File(realPath);
if (!up.exists()) {
up.mkdirs();
}
response.setCharacterEncoding("UTF-8");
Integer chunk = null;// 分割块数
Integer chunks = null;// 总分割数
String tempFileName = null;// 上传到服务器的临时文件名
String newFileName = null;// 最后合并后的新文件名
BufferedOutputStream outputStream = null;
if (ServletFileUpload.isMultipartContent(request)) {
try {
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(1024);
// factory.setRepository(new File(repositoryPath));// 设置临时目录
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8");
// upload.setSizeMax(5 * 1024 * 1024);// 设置附件最大大小,超过这个大小上传会不成功
List<FileItem> items = upload.parseRequest(request);
for (FileItem item : items) {
System.out.println("JSON="+item.getName());
//为了兼容bootstarp-input,添加文件名获取函数
if (item.getName()!=null) {
Random random=new Random();
int i=random.nextInt(9999);
tempFileName=i + item.getName();
System.out.println("item tempFileName="+item.getName());
}
//pluoadity使用代码
if (item.isFormField()) {// 是文本域

if (item.getFieldName().equals("name")) {
// if (item.getFieldName().equals("filename")) {
//System.out.println("name="+item.getString());
tempFileName = item.getString();
// System.out.println("临时文件名:" + tempFileName);
} else if (item.getFieldName().equals("chunk")) {
chunk = Integer.parseInt(item.getString());
// System.out.println("当前文件块:" + (chunk + 1));
} else if (item.getFieldName().equals("chunks")) {
chunks = Integer.parseInt(item.getString());
// System.out.println("文件总分块:" + chunks);
}
} else {// 如果是文件类型
if (tempFileName != null) {
String chunkName = tempFileName;
if (chunk != null) {
chunkName = chunk + "_" + tempFileName;
}
File savedFile = new File(realPath, chunkName);
item.write(savedFile);
}
}
}
System.out.println("tempFileName="+tempFileName);
newFileName = UUID.randomUUID().toString().replace("-", "").concat(".").concat(FilenameUtils.getExtension(tempFileName));
if (chunks == null) {// 如果不分块上传,那么只有一个名称,就是临时文件的名称
newFileName = tempFileName;
}
if (chunk != null && chunk + 1 == chunks) {
outputStream = new BufferedOutputStream(new FileOutputStream(new File(realPath, newFileName)));
// 遍历文件合并
for (int i = 0; i < chunks; i++) {
File tempFile = new File(realPath, i + "_" + tempFileName);
byte[] bytes = FileUtils.readFileToByteArray(tempFile);
outputStream.write(bytes);
outputStream.flush();
tempFile.delete();
}
outputStream.flush();
}
Map<String, Object> m = new HashMap<String, Object>();
m.put("status", true);
m.put("fileUrl", path + "/" + newFileName);
response.getWriter().write(JSON.toJSONString(m));
} catch (FileUploadException e) {
e.printStackTrace();
Map<String, Object> m = new HashMap<String, Object>();
m.put("status", false);
response.getWriter().write(JSON.toJSONString(m));
} catch (Exception e) {
e.printStackTrace();
Map<String, Object> m = new HashMap<String, Object>();
m.put("status", false);
response.getWriter().write(JSON.toJSONString(m));
} finally {
try {
if (outputStream != null) {
outputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}

注意红字部分为兼容的关键代码,其它的代码为plupload的分块上传代码,不用的可以删掉就可以了。

前台也放出给大家看看:
<div class="fileinput input-group">
<span class="input-group-addon">上传附件</span>
        <input id="file-Portrait1" multiple type="file" />
</div>

function initFileInput(ctrlName, uploadUrl) {    
    var control = $('#' + ctrlName); 
    control.fileinput({
     language: 'zh', //设置语言
        uploadUrl: uploadUrl, //上传的地址
        allowedFileExtensions : ['jpg', 'png','gif','doc','docx','wps','pdf'],//接收的文件后缀
        showUpload: true, //是否显示上传按钮
        showCaption: false,//是否显示标题
        //allowedPreviewTypes:['jpg', 'png','gif','pdf'],
        browseClass: "btn btn-primary", //按钮样式             
        previewFileIcon: "<i class='glyphicon glyphicon-king'></i>", 
    });
}

<%String contextPath = request.getContextPath();%>
$(function() {
initFileInput("file-Portrait1", "<%=contextPath%>/plupload?fileFolder=/userfile");
});

web.xml的servlet配置别忘记了
<!-- plUpload上传 -->
<servlet>
<servlet-name>PlUpload</servlet-name>
<servlet-class>sy.util.base.PlUploadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>PlUpload</servlet-name>
<url-pattern>/plupload</url-pattern>
</servlet-mapping>

记录结束,希望大家喜欢上漂亮的bootstrap-fileinput

0 0
原创粉丝点击