struts 上傳任意數量文件
在struts1.x中,若使用FormFile[]數組來做批量上傳并不能成功。
下面這種方法只是通過struts1.x中的MultipartRequestHandler來獲取<input type="file" />控件來達到批量上傳的目的
1.jsp頁面為
下面這種方法只是通過struts1.x中的MultipartRequestHandler來獲取<input type="file" />控件來達到批量上傳的目的
1.jsp頁面為
<html:file property="files(0)" />
<html:errors property="files" />
<div id="uploadFile"></div>
<a href=""> <input type="button" value="上傳更多"
onclick="addItem()" />
<script>
i=1;
function addItem(){
document.getElementById('uploadFile').innerHTML+='<input type=\\"file\\" name=\\"files('+i+')\\"><br/> ';
i++;
}
</script>
本文轉載自 http://www.itjianghu.net/120108/40916448564814888.htm
<html:errors property="files" />
<div id="uploadFile"></div>
<a href=""> <input type="button" value="上傳更多"
onclick="addItem()" />
<script>
i=1;
function addItem(){
document.getElementById('uploadFile').innerHTML+='<input type=\\"file\\" name=\\"files('+i+')\\"><br/> ';
i++;
}
</script>
2 form表單
//目的是不讓struts報錯
private List<FormFile> files = new ArrayList<FormFile>();
public List<FormFile> getFiles() {
return this.files;
}
private List<FormFile> files = new ArrayList<FormFile>();
public List<FormFile> getFiles() {
return this.files;
}
3.action為
//獲取formfile
ContentPublishForm contentPublishForm = (ContentPublishForm) form;
MultipartRequestHandler multipartRequestHandler = form
.getMultipartRequestHandler();
// 取得所有上傳文件的對象集合
Hashtable elements = multipartRequestHandler.getFileElements();
// 循環遍歷每一個文件
Collection values = elements.values();
int k = 0;
for (java.util.Iterator i = values.iterator(); i.hasNext();) {
FormFile file = (org.apache.struts.upload.FormFile) i.next();// 取得上傳的文件
if ("" != file.toString()) {
FileOutputStream fileOutput;
try {
String fileUrl = request
.getRealPath("//Image//"
+ file.getFileName());
fileOutput = new FileOutputStream(fileUrl);
fileOutput.write(file.getFileData());
fileOutput.flush();
fileOutput.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
ContentPublishForm contentPublishForm = (ContentPublishForm) form;
MultipartRequestHandler multipartRequestHandler = form
.getMultipartRequestHandler();
// 取得所有上傳文件的對象集合
Hashtable elements = multipartRequestHandler.getFileElements();
// 循環遍歷每一個文件
Collection values = elements.values();
int k = 0;
for (java.util.Iterator i = values.iterator(); i.hasNext();) {
FormFile file = (org.apache.struts.upload.FormFile) i.next();// 取得上傳的文件
if ("" != file.toString()) {
FileOutputStream fileOutput;
try {
String fileUrl = request
.getRealPath("//Image//"
+ file.getFileName());
fileOutput = new FileOutputStream(fileUrl);
fileOutput.write(file.getFileData());
fileOutput.flush();
fileOutput.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
本文轉載自 http://www.itjianghu.net/120108/40916448564814888.htm