网上看到比较细的解答,记录一下。http://www.iteye.com/problems/89011 正文:
jsp中
<s:file name="upload" label="上传的文件" />
action中,声明代码:
private File upload;
private String uploadContentType; // 文件的内容类型
private String uploadFileName; // 上传文件名
这里有个疑问, 文件名和文件类型是如何获取的?
约定,在struts2内部的的FileUploadInterceptor完成的
String[] fileName = multiWrapper.getFileNames(inputName);//得到请求的所有文件名
if (isNonEmpty(fileName)) {
// get a File object for the uploaded File
File[] files = multiWrapper.getFiles(inputName);
if (files != null && files.length > 0) {
List<File> acceptedFiles = new ArrayList<File>(files.length);
List<String> acceptedContentTypes = new ArrayList<String>(files.length);
List<String> acceptedFileNames = new ArrayList<String>(files.length);
String contentTypeName = inputName + "ContentType";//默认就是input名称+ContentType
String fileNameName = inputName + "FileName";//默认就是input名称+FileName
for (int index = 0; index < files.length; index++) {
if (acceptFile(action, files[index], fileName[index], contentType[index], inputName, validation, ac.getLocale())) {
acceptedFiles.add(files[index]);
acceptedContentTypes.add(contentType[index]);
acceptedFileNames.add(fileName[index]);
}
}
if (!acceptedFiles.isEmpty()) {
Map<String, Object> params = ac.getParameters();//添加到parameters中 这样就可以通过OGNL注入到action了
params.put(inputName, acceptedFiles.toArray(new File[acceptedFiles.size()]));
params.put(contentTypeName, acceptedContentTypes.toArray(new String[acceptedContentTypes.size()]));
params.put(fileNameName, acceptedFileNames.toArray(new String[acceptedFileNames.size()]));
}
}