通过 $.ajaxFileUpload 实现struts的异步上传功能

  • Post author:
  • Post category:其他


最近在struts项目开发中遇到一个上传问题,发现struts对MultipartFile的不友好性,特找到了DiskFileItemFactory和ServletFileUpload替换方法,具体开发代码如下:

jsp代码

function uploadExcel(){


$.ajaxFileUpload({


url : ‘${pageContext.request.contextPath}/fileUpload.do’,

secureuri : false,

fileElementId : ‘upload’,// file标签的id

dataType : ‘text’,// 返回数据的类型

type : ‘POST’,

success : function(data, status) {

console.log(data);

//对返回过来的数据作处理

/* var result = data.toString().substr(5, data.length – 11);

var json = $.parseJSON(result);

if (!json.result) {


alertErrorAtBottomRight(json.errorMsg);

} else {


var data = json.data;

alertSuccessAtBottomRight(“文件导入成功,”+data);

//上传成功后,对文本框的数据清空

resetForm(‘add_acct_export’);

//上传成功后,对弹出框作隐藏处理

$(“#export-account”).modal(“hide”);

} */

var isIE = navigator.userAgent.indexOf(“compatible”) > -1 && userAgent.indexOf(“MSIE”) > -1;

if(isIE) {    // 此处判断是否是IE

$(‘#upload’).replaceWith($(‘#upload’).clone(true));

} else {


$(‘#upload’).val(”);

}

},

error : function(data, status, e) {


alertErrorAtBottomRight(e);

}

});

Control  层代码

public ActionForward fileUpload(ActionMapping mapping, ActionForm form, HttpServletRequest request,

HttpServletResponse response) throws Exception {

DiskFileItemFactory factory = new DiskFileItemFactory();

ServletFileUpload upload = new ServletFileUpload(factory);

upload.setHeaderEncoding(“UTF-8”);

if (!ServletFileUpload.isMultipartContent(request)) {


return null;

}

try {


List<FileItem> list = upload.parseRequest(request);

for (FileItem item : list) {


if (item.isFormField()) {


log.info(“fileUpload format is error”);

}else{


String fileName = item.getName();

if (fileName != null && fileName.indexOf(“.xls”) < 0) {


return null;

}

if (fileName==null||fileName.trim().equals(“”)) {


continue;

}

//                    items.add(item);

InputStream is = item.getInputStream();

Workbook wb = Workbook.getWorkbook(is);

int sheet_size = wb.getNumberOfSheets();

for (int index = 0; index < sheet_size; index++) {


Sheet sheet = wb.getSheet(index);

if(sheet.getRows()<=1) {


return null;

}

for (int i = 1; i < sheet.getRows(); i++) {


String orderNo = null;

List<String> innerList=new ArrayList<String>();

for (int j = 0; j < sheet.getColumns(); j++) {


innerList.add(sheet.getCell(j, i).getContents());

if(j==3) {


orderNo=sheet.getCell(j, i).getContents();

}

}

Map oldeOrder = null;

String objectId = null;

Map<String, String> param = new HashMap<String, String>();

int num = myZfbYsdzDetailNewFacade.importExecle(innerList,oldeOrder,objectId,param);

……

}

}

}

}

return null;

} catch (Exception e) {


e.printStackTrace();

return null;

}

}



版权声明:本文为EleganceAndNobility原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。