问题:动态添加file输入框,按照一般,前台可以用[i]数组,Action用List接收
,struts2会绑定好数据,这时候,文件可以以List获得,但是多文件的name,没法采用这种方法获得List
如:
var imgCount=0;
// var attach= Ext.ComponentQuery.query('filefield[name^=attach]');
function addFile(){
var form = Ext.getCmp("form");
var field= {
margin:'10px',
xtype: 'fieldcontainer',
layout: { type: 'hbox' },
fieldDefaults: { labelAlign: 'right', labelWidth: 90, width: 290 },
//items: [inventoryField ]
items: [ {
xtype: 'filefield',
// name: 'attach['+imgCount+']',
name: 'attach',
fieldLabel: '图片',
allowBlank: false,
anchor: '100%',
buttonText: '选择图片',
emptyText: '--请选择图片--'
},{
xtype : 'button',
text : '删除',
iconCls : 'silk_page_add',
handler : function(button ) {
button .up('#form').remove(button.up('fieldcontainer'));
}
}]
};
form.add(field);
imgCount++;
}
});
解决:
xtype: 'filefield',
// name: 'attach['+imgCount+']', //注释掉
name: 'attach',
name不用拼接,直接用同一个name。后台直接以List接收
private List<File> attach;
private List<String> attachFileName;
private List<String> attachContentType;
----------------------------------
上传文件到目录的方法
/**
* 上传文件
* @param file
* @param curUserId
* @return 文件相对目录
* @throws Exception
*/
private String uploadDir(File file,String imageName,String curUserId) throws Exception{
//基于myFile创建一个文件输入流
InputStream is = new FileInputStream(file);
String filePath = this.getClass().getClassLoader().getResource("/")
.getPath();
int index = filePath.indexOf("webapps");
// int index = filePath.indexOf("WEB-INF");
String contentPath = filePath.substring(0, index);
String savepath = contentPath + "upload" + "/" + curUserId + "/";
savepath = savepath.replace("%20", " ");
// ServletActionContext.getServletContext().getRealPath("img");
// 设置目标文件
File toFile = new File(savepath);
if (!toFile.exists()) {
toFile.mkdirs();
}
Date date = new Date();
// SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmsssss");
// String dateName = formatter.format(date);
String dateName = UUID.randomUUID().toString();
String newName = dateName + imageName;
// 创建一个输出流
OutputStream os = new FileOutputStream(savepath + newName);
//设置缓存
byte[] buffer = new byte[1024];
int length = 0;
//读取myFile文件输出到toFile文件中
while ((length = is.read(buffer)) > 0) {
os.write(buffer, 0, length);
}
//关闭输入流
is.close();
//关闭输出流
os.close();
return "/" + curUserId + "/" + newName;
// data.setFilePath("/" + curUserId + "/" + newName);
}