Webwork implements file upload and download code explanation _ javascript skills

Source: Internet
Author: User
WebWork also provides a friendly Interceptor to upload files. This allows us to focus on designing and implementing business logic, this article focuses on the implementation of the next framework for upload and download in the Process of upload and download. It mainly introduces the knowledge of webwork file upload and download in three aspects, including the following three aspects:

1. Request Packaging
2. Get the parsing class for File Upload
3. Practical configuration and use of the project

Web upload and download should be a common requirement, whether it is a small website or a large concurrent transaction website. WebWork also provides a friendly Interceptor to upload files. This allows us to focus on designing and implementing business logic, when uploading and downloading, follow the implementation of the Framework upload and downloading.

1. Request Packaging

• Each time a client requests an Action, the WebWork scheduling class ServletDispatcher. service () method is called.

For details about the specific process, see: http://www.jb51.net/article/79053.htm "> Webwork Action call Method

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 request MultipartRequestWrapper! "; Log. error (message, e); sendError (request, response, 500, new ServletException (message, e ));}}

Let's take a look at what the wrapRequest method has done:

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, it determines whether the passed request has been encapsulated with MultiPartRequestWrapper. If yes, it will be returned directly.
• Otherwise, determine whether the Content Type in the request header is a multipart/form data request. If yes, package the request into the MultiPartRequestWrapper Type of WebWork, this type inherits from HttpServletRequestWrapper.

The MultiPartRequest. isMultiPart () method is implemented 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");}

• Configure the temporary storage directory of the file and the maximum upload size in webwork. properties, which is actually useful at this time.
• The parameters passed in when the MultiPartRequestWrapper object is created are obtained by getSaveDir () and getMaxSize () methods.
• The webwork in the configuration will be searched in the method. multipart. saveDir, webwork. multipart. maxSize attribute. If it is found, use the temporary directory specified by this attribute and the maximum content uploaded. If it is not found, use the temporary directory of the environment.

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 at how the MultiPartRequestWrapper constructor wraps the request:

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 determines whether the input request is a subclass of the MultiPartRequest abstract class. If so, it directly references its MultiPartRequest type variable to the request.

• Otherwise, the WebWork. multipart. parser attribute configured in webwork is read. This attribute determines what file upload is implemented in Webwork. If not specified, the implementation of PellMultiPartRequest is used by default.

• After finding the configured class, WebWork creates the class instance through Java reflection. All supported classes are inherited from MultiPartRequest. After the instance is created, it is transformed upwards and assigned multi members to MultiPartRequestWrapper.

• WebWork File Upload encapsulates several general FileUpload lib, which is not implemented by yourself.

• It includes three implementations: pell, cos, and apache common. WebWork encapsulates these three packages and provides a common access interface MultiPartRequest, the implementation details are PellMultiPartRequest, CosMultiPartRequest, and JakartaMultiPartRequest.

• Jakarta supports multiple files using the same HTTP parameter name. If you directly use WebWork's FileUpload interceptor, pell is recommended, because when you upload a file with a Chinese file name, only the pell package will get the Chinese file name correctly, apache common changes 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 is powerful, 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:

 
  /Result. jsp
 
 
  /Result. jsp
  
  
 // The interception stack required for webwok upload// Define the interception Stack
 
   
  
 // Interceptor corresponding to the interception Stack
 
  

• The front-end uses the stable and powerful Ajaxupload, which is not mentioned here. The official website: jQuery AjaxUpload uploads Image Code

• 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 execute Action.
• Determine whether the MultiPartRequestWrapper contains an error during the File Upload process. Return the error message to the client and do not continue to call the Action.
• If none of the above conditions are met, traverse the parameters of the uploaded file in MultiPartRequestWrapper and put the file name and content type in the parameter map of Action, for subsequent business operations.
• In the fileupload interceptor function of WebWork, the File provided by WebWork is only a temporary File and will be automatically deleted after the Action is executed. You must handle File storage problems in the Action, it can also be written to a directory on the server or saved 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.

The code above introduces you to the knowledge of Webwork for file upload and download, and hopes to help you.

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.