我正在嘗試使用apache commons文件上傳庫從jsp/ajax上傳文件。下面是代碼:下載共享資料文件上傳
JSP:
function importFileListForm()
{
var html = "<div><h3>Add File</h3></div>";
html += '<table style="margin-top:20px;" width="100%"><tbody>';
html += '<tr><td>Choose File</td><td><input id="fileId" type="file" name="fileName" required size="50"/></td><td></td></tr>';
html += '</tbody></table>';
$("#dialog-modal-content").html(html);
$(function() {
$("#dialog-modal").dialog({
height: 300,
width: 600,
modal: true,
buttons: {
"Cancel": function() {
$(this).dialog("close");
},
"Submit": function() {
importFileConfirm($("#fileId").val());
}
}
});
});
}
function importFileConfirm(file)
{
var url = "/config/fileManageAction.do?method=importFile&file=" +file;
var req = new FormData();
req.append("f", file);
$.ajax({
type: 'POST',
data: req,
url: url,
processData: false,
contentType: false,
success: function(data) {console.log(data);}
});
}
我的動作類方法:
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(maxSize);
factory.setRepository(new File("/production/cpu/temp.xlsx"));
ServletFileUpload upload = new ServletFileUpload(factory);
// maximum file size to be uploaded.
upload.setSizeMax(maxSize);
try{
List fileItem = upload.parseRequest(request);
java.lang.System.out.println("List "+fileItem.size());
// Part filePart = request.getPart("file");
// java.lang.System.out.println("File Part "+filePart);
// Process the uploaded file items
Iterator i = fileItem.iterator();
while(i.hasNext()){
FileItem fi = (FileItem)i.next();
if(!fi.isFormField()){
java.lang.System.out.println("Fi "+fi);
String fieldname = fi.getFieldName();
java.lang.System.out.println("FieldName "+fieldname);
String filename = FilenameUtils.getName(fi.getName());
java.lang.System.out.println("File Name "+fi.getString());
InputStream filecontent = fi.getInputStream();
}else{
java.lang.System.out.println("not a form field");
java.lang.System.out.println("Fi "+fi);
String fileName = fi.getName();
java.lang.System.out.println("File Name: "+fileName);
}
}
}catch(Exception e){
java.lang.System.out.println("Exception occured "+e);
e.printStackTrace();
}
// }
}
但在我的文件項目我只得到字段名和fi.getName()
正在恢復空值。有人能說出我缺少的東西嗎?我不能用getParts()
函數,因爲我的tomcat不支持它。
標準ajax不允許文件上傳。通常的解決方法是將文件輸入的dom元素複製到隱藏的iframe中,並從那裏進行常規上傳。 – 2014-10-16 14:10:40
@MarcB,謝謝你的回覆。你能指點我一個例子嗎? – user2052801 2014-10-16 14:12:32