// 創(chuàng)建一個FormPanel組件實例
var loginForm = new Ext.FormPanel({
id:'loginForm',// formPanel組件的ID
width:600,// 組件寬度
height:300,// 組件高度
frame:true,
fileUpload: true,
enctype:'multipart/form-data',
//實現(xiàn)非AJAX提交表單一定要加下面的兩行!
onSubmit: Ext.emptyFn,
method:'POST',
align:'center',// 組件居左布局,還有right和center兩個值可以選擇
name: 'loginForm', //組件名稱
labelAlign:"left",//讓label居右
labelWidth:120,//定義label的寬度
items:[{
xtype: "textfield",
inputType:'file',
name: 'processFile',
fieldLabel: '文件',
allowBlank:false,
anchor:'95%'
public void deploy(HttpServletRequest request, HttpServletResponse response)
throws Exception {
request.setCharacterEncoding("utf-8");
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
String tmpDir = getServletContext().getRealPath("/temp");// 初始化上傳文件的臨時寄放目錄
String uploadPath = getServletContext().getRealPath("/upload");// 初始化上傳文件后的保存
try {
if (ServletFileUpload.isMultipartContent(request)) {
DiskFileItemFactory factory = new DiskFileItemFactory();
//指定在內(nèi)存中緩存數(shù)據(jù)大小,單位為byte,這里設(shè)為1Mb
factory.setSizeThreshold(1 * 1024 * 1024);
//設(shè)置一旦文件大小超過getSizeThreshold()的值時數(shù)據(jù)存放在硬盤的目錄
factory.setRepository(new File(tmpDir));
ServletFileUpload sfu = new ServletFileUpload(factory);
// 指定單個上傳文件的最大尺寸,單位:字節(jié),這里設(shè)為5Mb
sfu.setFileSizeMax(100 * 1024 * 1024);
//指定一次上傳多個文件的總尺寸,單位:字節(jié),這里設(shè)為10Mb
sfu.setSizeMax(100 * 1024 * 1024);
sfu.setHeaderEncoding("UTF-8"); //設(shè)置編碼,因為我的jsp頁面的編碼是utf-8的
FileItemIterator fii = sfu.getItemIterator(request);// 解析request請求
uploadPath = uploadPath + "\\jbpm\\"; // 選定上傳的目錄此處為當(dāng)前目錄
if (!new File(uploadPath).isDirectory()){
new File(uploadPath).mkdirs(); //選定上傳的目錄此處為當(dāng)前目錄,沒有則創(chuàng)建
}
int index = 0;
while (fii.hasNext()) {
FileItemStream fis = fii.next();// 從集合中獲得一個文件流
if (!fis.isFormField() && fis.getName().length() > 0) {// 過濾掉表單中非文件域
String fileName = fis.getName();// 獲得上傳文件的文件名
BufferedInputStream in = new BufferedInputStream(fis.openStream());
BufferedOutputStream out = new BufferedOutputStream(
new FileOutputStream(new File(uploadPath + "\\" + fileName)));
Streams.copy(in, out, true); // 開始把文件寫到你指定的上傳文件夾
index++;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
response.setContentType("text/html");
response.getWriter().print("{success:true}");
}
上傳文件為空:因為:
<filter-mapping>
<!--攔截所有的URL請求-->
<filter-name>struts2</filter-name>
<!--上傳文件會不起作用-->
<!-- url-pattern>/*</url-pattern -->
<url-pattern>*.action</url-pattern>
</filter-mapping>
原因就是因為在web.xml中配置了Struts的filter
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
改成
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>*.action</url-pattern>
</filter-mapping>
就可以了