1. 程式人生 > >struts2上傳檔案時,關於在action裡面獲取上傳檔案的檔名

struts2上傳檔案時,關於在action裡面獲取上傳檔案的檔名

在struts2中有個檔案上傳的攔截器 FileUploadInterceptor 在它的intercept中我們可以找到答案。  

貼原始碼:

public String intercept(ActionInvocation invocation) throws Exception {
        ActionContext ac = invocation.getInvocationContext();

        HttpServletRequest request = (HttpServletRequest) ac.get(ServletActionContext.HTTP_REQUEST);

        if (!(request instanceof MultiPartRequestWrapper)) {
            if (LOG.isDebugEnabled()) {
                ActionProxy proxy = invocation.getProxy();
                LOG.debug(getTextMessage("struts.messages.bypass.request", new String[]{proxy.getNamespace(), proxy.getActionName()}));
            }

            return invocation.invoke();
        }

        ValidationAware validation = null;

        Object action = invocation.getAction();

        if (action instanceof ValidationAware) {
            validation = (ValidationAware) action;
        }

        MultiPartRequestWrapper multiWrapper = (MultiPartRequestWrapper) request;

        if (multiWrapper.hasErrors()) {
            for (String error : multiWrapper.getErrors()) {
                if (validation != null) {
                    validation.addActionError(error);
                }
            }
        }

        // bind allowed Files
        Enumeration fileParameterNames = multiWrapper.getFileParameterNames();
        while (fileParameterNames != null && fileParameterNames.hasMoreElements()) {
            // get the value of this input tag
            String inputName = (String) fileParameterNames.nextElement();//獲取頁面 input 的name值

            // get the content type
            String[] contentType = multiWrapper.getContentTypes(inputName);//得到請求的所有型別

            if (isNonEmpty(contentType)) {
                // get the name of the file from the input tag
                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,分別表示檔案集合、型別集合、檔名集合
                        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";
                        String fileNameName = inputName + "FileName";//頁面 input 的name值+"FileName" 就是儲存檔名的變數名。例如
				       前臺頁面是:<input name="myfile" type="file" />。在action中我們就可以定義一個myfileFilename變數,並定義其get/set方法。
			  然後我們就可以直接使用myfileFilename得到上傳檔案的名稱。
		        //下面的for迴圈就是 給前面建立的三個集合賦值,如果有的話
						for (int index = 0; index < files.length; index++) {
							if (acceptFile(action, files[index], fileName[index], contentType[index], inputName, validation)) {
								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()]));
						} 
					} 
				}else{
					if (LOG.isWarnEnabled()) { 
						LOG.warn(getTextMessage(action, "struts.messages.invalid.file", new String[]{inputName})); 
					} 
				} 
			}else{
				if (LOG.isWarnEnabled()) {
					LOG.warn(getTextMessage(action, "struts.messages.invalid.content.type", new String[]{inputName})); 
				} 
			} 
		} // invoke action return invocation.invoke(); 
}