Webwork learning path (7) file upload/download and webwork File Upload

Source: Internet
Author: User

Webwork learning path (7) file upload/download and webwork File Upload

Web upload and download should be a common requirement, whether it is a small website or a large concurrent transaction website.WebWorkOf course, it also provides a friendly Interceptor to upload files, so that we can focus on the design and implementation of business logic, the implementation of the next framework upload and download is followed in the implementation of upload and download. The summary in this blog is as follows.

1. Request Packaging
  • Each client requestActionWill callWebWorkSchedulingServletDispatcher. service ()Method.

For detailed process, see: http://www.cnblogs.com/java-class/p/5155793.html

Public void service (HttpServletRequest request, HttpServletResponse response) throws ServletException {try {if (encoding! = Null) {try {request. setCharacterEncoding (encoding);} catch (Exception localException) {}} if (locale! = Null) {response. setLocale (locale);} if (this. paramsWorkaroundEnabled) {request. getParameter ("foo");} request = wrapRequest (request); // encapsulate the request serviceAction (request, response, getNameSpace (request), getActionName (request ), getRequestMap (request), getParameterMap (request), getSessionMap (request), getApplicationMap ();} catch (IOException e) {String message = "cocould not wrap servlet requ Est with MultipartRequestWrapper! "; Log. error (message, e); sendError (request, response, 500, new ServletException (message, e ));}}

Let's take a lookWrapRequestMethod:

    protected HttpServletRequest wrapRequest(HttpServletRequest request) throws IOException {        if ((request instanceof MultiPartRequestWrapper)) {            return request;        }        if (MultiPartRequest.isMultiPart(request)) {            request = new MultiPartRequestWrapper(request, getSaveDir(), getMaxSize());        }        return request;    }
  • First, the uploadedRequestIs it encapsulated?MultiPartRequestWrapperIf yes, it will be returned directly.
  • Otherwise, Judge again.RequestIn the header informationContent TypeIs it a multipart/form data request?RequestPackagedWebWorkYour ownMultiPartRequestWrapperType, which inheritsHttpServletRequestWrapper.

MultiPartRequest. isMultiPart ()The method is as follows:

 public static boolean isMultiPart(HttpServletRequest request){        String content_type = request.getHeader("Content-Type");        return content_type != null && content_type.startsWith("multipart/form-data");    }
  • InWebwork. propertiesThe temporary storage directory of the configuration file and the maximum upload size are actually used at this time.
  • CreateMultiPartRequestWrapperWhen an object is passed inGetSaveDir ()AndGetMaxSize ()Method obtained.
  • FindWebwork. multipart. saveDir, webwork. multipart. maxSizeIf the attribute is found, the temporary directory specified by this attribute and the maximum content uploaded are used. If the attribute is not found, the temporary directory of the environment is used.

The specific implementation is as follows:

    protected String getSaveDir() {        String saveDir = Configuration.getString("webwork.multipart.saveDir").trim();        if (saveDir.equals("")) {            File tempdir = (File) getServletConfig().getServletContext().getAttribute("javax.servlet.context.tempdir");            log.info("Unable to find 'webwork.multipart.saveDir' property setting. Defaulting to javax.servlet.context.tempdir");            if (tempdir != null) {                saveDir = tempdir.toString();            }        } else {            File multipartSaveDir = new File(saveDir);            if (!multipartSaveDir.exists()) {                multipartSaveDir.mkdir();            }        }        if (log.isDebugEnabled()) {            log.debug("saveDir=" + saveDir);        }        return saveDir;    }
2. Get the parsing class for File Upload

Let's take a look.MultiPartRequestWrapperHow to wrap the constructorRequestOf:

    public MultiPartRequestWrapper(HttpServletRequest request, String saveDir, int maxSize) throws IOException {        super(request);        if ((request instanceof MultiPartRequest)) {            this.multi = ((MultiPartRequest) request);        } else {            String parser = "";            parser = Configuration.getString("webwork.multipart.parser");            if (parser.equals("")) {                log.warn("Property webwork.multipart.parser not set. Using com.opensymphony.webwork.dispatcher.multipart.PellMultiPartRequest");                parser = "com.opensymphony.webwork.dispatcher.multipart.PellMultiPartRequest";            } else if (parser.equals("pell")) {                parser = "com.opensymphony.webwork.dispatcher.multipart.PellMultiPartRequest";            } else if (parser.equals("cos")) {                parser = "com.opensymphony.webwork.dispatcher.multipart.CosMultiPartRequest";            } else if (parser.equals("jakarta")) {                parser = "com.opensymphony.webwork.dispatcher.multipart.JakartaMultiPartRequest";            }            try {                Class baseClazz = MultiPartRequest.class;                Class clazz = Class.forName(parser);                if (!baseClazz.isAssignableFrom(clazz)) {                    addError("Class '" + parser + "' does not extend MultiPartRequest");                    return;                }                Constructor ctor = clazz.getDeclaredConstructor(new Class[] { Class.forName("javax.servlet.http.HttpServletRequest"), String.class, Integer.TYPE });                Object[] parms = { request, saveDir, new Integer(maxSize) };                this.multi = ((MultiPartRequest) ctor.newInstance(parms));            } catch (ClassNotFoundException e) {                addError("Class: " + parser + " not found.");            } catch (NoSuchMethodException e) {                addError("Constructor error for " + parser + ": " + e);            } catch (InstantiationException e) {                addError("Error instantiating " + parser + ": " + e);            } catch (IllegalAccessException e) {                addError("Access errror for " + parser + ": " + e);            } catch (InvocationTargetException e) {                addError(e.getTargetException().toString());            }        }    }
  • First, it judges the inputRequestIs it true?MultiPartRequestThe subclass of an abstract class.MultiPartRequestType Variable referenceRequest.
  • Otherwise, readWebWorkConfiguredWebwork. multipart. parserAttribute, which is determinedWebworkWhat is used internally to upload files. If not specifiedPellMultiPartRequest.
  • After finding the configured class,WebWorkCreates an instance of this class through Java reflection. All supported classes are fromMultiPartRequestAfter the instance is createdMultiPartRequestWrapper.
  • WebWork File Upload encapsulates several general FileUpload lib, which is not implemented by yourself.
  • It includes three implementations: pell, cos, and apache common,WebWorkThese three packages are encapsulated to provide a common access interface.MultiPartRequestAnd the implementation details are as follows:PellMultiPartRequest, CosMultiPartRequest, and JakartaMultiPartRequest.
  •  JakartaMultiple files can use the same HTTP parameter name. If you directly useWebWorkOfFileUploadPell is recommended for Interceptor, because when you upload a file with a Chinese file name, only the pell package will correctly obtain the Chinese file name, and apache common will change the file name to xxx. the name of a file such as tmp, And cos Will be garbled, so the only choice is pell.
  • Cos has powerful functions, but WebWork encapsulation makes it lose many features. cos needs to set character encoding for request. The encapsulation of WebWork is not set, which leads to the cos garbled problem. Of course, if you use cos separately, this type of problem will be avoided.
3. Practical configuration and use of the project
  • Configuration File
Action configuration: <action name = "uploadAttach" class = "..... attach. action. uploadAttach "caption =" Upload attachment "> <result name =" success "type =" dispatcher "> <param name =" location ">/result. jsp </param> </result> <result name = "error" type = "dispatcher"> <param name = "location">/result. jsp </param> </result> <interceptor-ref name = "defaultStack"/> <interceptor-ref name = "fileUploadStack"/> // interception stack required for webwok upload </action> // stack interception definition <interceptor-stack name = "fileUploadStack"> <interceptor-ref name = "fileUpload"/> <interceptor-ref name = "params" /> </interceptor-stack> // interceptor corresponding to the interception stack <interceptor name = "fileUpload" class = "com. opensymphony. webwork. interceptor. fileUploadInterceptor "/> <interceptor name =" params "class =" com. opensymphony. xwork. interceptor. parametersInterceptor "/>
  • Front-end use more stable, more powerful Ajaxupload here is not much said, there are official site: http://www.cnblogs.com/dabaopku/archive/2011/06/29/2092833.html
  • Through the encapsulation of Webwork upload requests and the acquisition of resolution classes, all foreplays are ready. The specific implementation of the upload interceptor is as follows:
public String intercept(ActionInvocation invocation) throws Exception {if (!(ServletActionContext.getRequest() instanceof MultiPartRequestWrapper)) {            if (log.isDebugEnabled()) {                log.debug("bypass " + invocation.getProxy().getNamespace() + "/" + invocation.getProxy().getActionName());            }            return invocation.invoke();        }        Action action = invocation.getAction();        ValidationAware validation = null;        if ((action instanceof ValidationAware)) {            validation = (ValidationAware) action;        }        MultiPartRequestWrapper multiWrapper = (MultiPartRequestWrapper) ServletActionContext.getRequest();        if (multiWrapper.hasErrors()) {            Collection errors = multiWrapper.getErrors();            Iterator i = errors.iterator();            while (i.hasNext()) {                String error = (String) i.next();                if (validation != null) {                    validation.addActionError(error);                }                log.error(error);            }        }        Enumeration e = multiWrapper.getFileParameterNames();        while ((e != null) && (e.hasMoreElements())) {            String inputName = (String) e.nextElement();            String[] contentType = multiWrapper.getContentTypes(inputName);            String[] fileName = multiWrapper.getFileNames(inputName);            File[] file = multiWrapper.getFiles(inputName);            if (file != null) {                for (int i = 0; i < file.length; i++) {                    log.info("file " + inputName + " " + contentType[i] + " " + fileName[i] + " " + file[i]);                }            }            if (file == null) {                if (validation != null) {                    validation.addFieldError(inputName, "Could not upload file(s). Perhaps it is too large?");                }                log.error("Error uploading: " + fileName);            } else {                invocation.getInvocationContext().getParameters().put(inputName, file);                invocation.getInvocationContext().getParameters().put(inputName + "ContentType", contentType);                invocation.getInvocationContext().getParameters().put(inputName + "FileName", fileName);            }        }        String result = invocation.invoke();        for (Enumeration e1 = multiWrapper.getFileParameterNames(); e1 != null && e1.hasMoreElements();) {            String inputValue = (String) e1.nextElement();            File file[] = multiWrapper.getFiles(inputValue);            for (int i = 0; i < file.length; i++) {                File f = file[i];                log.info("removing file " + inputValue + " " + f);                if (f != null && f.isFile())                    f.delete();            }        }        return result;    }
  • First, determine whether the current request contains multimedia requests. If yes, log and executeAction.
  • Then judge the File Upload ProcessMultiPartRequestWrapperIndicates whether an error exists. The error message is returned to the client.Action.
  • If none of the above conditions are met, traverseMultiPartRequestWrapperAnd put the file name and content typeActionIn the map parameter for subsequent business classes to operate.
  • InWebWorkOfFileuploadIn the interceptor function, the File provided by the interceptor is only a temporary File. After the Action is executed, it will be automatically deleted. you mustActionOr write to a directory on the server or save it to the database. If you want to write the file to a directory on the server, you must handle the problem of the same name as the file. However, in fact, the cos package already provides automatic renaming rules for file names.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.