<input type="file" id="upload" name="upload"/> 這個name就是與Action的屬性對應
private File upload; private String uploadFileName; private String uploadContentType; public void setUpload(File upload) { this.upload = upload; } public void setUploadFileName(String uploadFileName) { this.uploadFileName = uploadFileName; } public void setUploadContentType(String uploadContentType) { this.uploadContentType = uploadContentType; }
特 別注意:,<s:file/>標誌不單單是綁定到upload,還有uploadContentType(上傳文件的MIME類型)和 uploadFileName(上傳文件的文件名,該文件名不包括文件的路徑)。所以,<s:file name="xxx" />對應Action類裏面的xxx、xxxContentType和xxxFileName三個屬性。 java
<s:file name="upload" label="上傳的文件" />
action中,聲明代碼: app
private File upload; private String uploadContentType; // 文件的內容類型 private String uploadFileName; // 上傳文件名
這裏有個疑問, 文件名和文件類型是如何獲取的? jsp
約定,在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()])); } }
參考文檔: this
http://blog.163.com/linfenliang@126/blog/static/127857195201171205937621/ spa