ExtJS部分的代码如下:
Ext.onReady(function(){
var loadform = new Ext.form.FormPanel({
renderTo:'file',
labelAlign: 'right',
title: '文件上传',
labelWidth: 60,
frame:true,
url: './upload.do?cmd=uploadFiles',//fileUploadServlet
width: 300,
height:200,
fileUpload: true,
items: [{
xtype: 'textfield',
id:'files',
fieldLabel: '文件名',
name: 'files',
inputType: 'file'//文件类型
}],
buttons: [{
text: '上传',
handler: function() {
loadform.getForm().submit({
method:'POST',
success: function(loadform,action){
Ext.Msg.alert('信息', action.result.info);
},
failure: function(){
Ext.Msg.alert('错误',action.result.info);
}
});
}
}]
});
});
Action部份的代码如下:
public static final String UPLOAD_FILE_PATH = "F:\\p_w_picpath\\"; // 文件上传后,保存的位置
/**
* 实现文件上传
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws Exception
*/
public ActionForward executeUploadFiles(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
PrintWriter out = response.getWriter();
DictInfoForm dictInfoForm=(DictInfoForm)form;
System.out.println(dictInfoForm.getFiles().getFileName());
FormFile uploadFile = dictInfoForm.getFiles();
//得到文件名
String fileName = uploadFile.getFileName();
//得到文件大小
int fileSize = uploadFile.getFileSize();
System.out.println("FileName = " + fileName);
System.out.println("FileSize=" + fileSize);
boolean result = true;
try{
//得到文件的输入流
InputStream is = uploadFile.getInputStream();
//上传文件
uploadFile(fileName,is);
}catch(IOException ex){
ex.printStackTrace();
//假如上传文件失败,设置一个失败的标记位
result = false;
}
if(result){
out.write("{success:true,info:'方件上传成功'}");
} else {
out.write("{success:false,info:'方件上传成功'}");
}
return mapping.findForward("");
}
/**
* 上传文件
* @param fileName
* @param is
* @throws IOException
*/
private void uploadFile(String fileName,InputStream is) throws IOException{
OutputStream os = new FileOutputStream(UPLOAD_FILE_PATH + fileName);
//8k缓存数据
byte[] buffer = new byte[1024 * 8];
//设置读进缓存的字节数
int len;
while((len=is.read(buffer))!=-1){
//将缓存数据写入磁盘
os.write(buffer,0,len);
}
//关闭输出流
os.close();
//关闭输入流
is.close();
}