WebWork implementation File upload download code detailed _javascript Tips

Source: Internet
Author: User
Tags cos locale tmp file

This article mainly from three aspects to introduce webwork file upload download knowledge, including the following three aspects:

1. Packaging Request Requests
2. Get file upload the Analytic class
3. Project actual deployment and use

Web uploads and downloads should be a common requirement, whether it be a small web site or a large concurrent-access trading site. WebWork Of course also provides a very friendly interceptor to achieve the upload of files, so that we can focus on the design and implementation of business logic, in the implementation of upload and download when the following frame upload download implementation.

1. Packaging Request Requests

• The WebWork dispatch class Servletdispatcher.service () method is invoked each time the client requests an Action.

Specific process Please refer to: Detailed WebWork method of action call

public void Service (HttpServletRequest request, httpservletresponse response) throws Servletexception {
try {
if (encoding!= null) {
try {
request.setcharacterencoding (encoding);
} catch (Exception localexception) { c6/>}
}
if (locale!= null) {
response.setlocale (locale);
}
if (this.paramsworkaroundenabled) {
request.getparameter ("foo");
}
Request = Wraprequest (request); Encapsulates request requests
serviceaction (request, response, GetNamespace (requests), Getactionname (Request), Getrequestmap ( Request), Getparametermap (Request), Getsessionmap (Request), Getapplicationmap ());
catch (IOException e) {
String message = ' could not wrap servlet request with multipartrequestwrapper! ';
Log.error (message, e);
Senderror (Request, Response, new servletexception (message, E));

Let's look at what the Wraprequest method does:

Protected HttpServletRequest wraprequest (HttpServletRequest request) throws IOException {
if (Request instanceof Multipartrequestwrapper)) {return
request;
}
if (Multipartrequest.ismultipart) {
request = new Multipartrequestwrapper (Request, Getsavedir (), Getmaxsize ());
}
return request;
}

• First of all, judge the incoming request is not already encapsulated good multipartrequestwrapper, if it is directly returned.
* Otherwise judge request's head information inside the ContentType is not a multiple type parameter (multipart/formdata) request, if it is to be packaged into WebWork own multipartrequestwrap Per type, this type inherits 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");
}

• In Webwork.properties, the temporary storage directory of the configuration files, and the maximum upload size, in fact, at this time to play a role.
• The parameters passed in when the Multipartrequestwrapper object was created are obtained by the Getsavedir () and Getmaxsize () methods.
• In the method will look for the configuration inside the Webwork.multipart.saveDir, webwork.multipart.maxSize properties, find the use of the property specified in the temporary directory and upload the maximum content, did not find a temporary directory to use the environment.

Specifically implemented 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" the "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 file upload the Analytic class

Let's take a look at how the Multipartrequestwrapper constructor wraps the request:

Public Multipartrequestwrapper (HttpServletRequest request, String savedir, int maxSize) throws IOException {super (Reque
ST);
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 incoming request is a subclass of the Multipartrequest abstract class, and if so, simply references its own multipartrequest type of variable to request.

• Otherwise read the Webwork.multipart.parser property of the WebWork configuration, which determines what implementation files are uploaded within WebWork. If not specified, the Pellmultipartrequest implementation is used by default.

• Once the configured class is found, WebWork creates an instance of the class through Java reflection. All supported classes inherit from Multipartrequest, create the instance and then transition upward and give multipartrequestwrapper members multi.

WebWork's file upload encapsulates several generic fileupload lib, not implemented by itself.

• It includes three implementations of the Pell,cos,apache Common, webwork encapsulates these three packages, provides a common access interface Multipartrequest, the details are pellmultipartrequest, Cosmultipartrequest, Jakartamultipartrequest.

Jakarta supports multiple files using the same HTTP parameter name. If you use WebWork's FileUpload interceptor directly, you recommend using Pell, because when you upload a file in Chinese file name, only the Pell package will get the name of the Chinese file correctly, Apache Common will change the file name to xxx.tmp file name, and Cos will be garbled, so our only choice is Pell.

Cos's function is quite powerful, WebWork's encapsulation has made it lose a lot of functions, cos need to set request character encoding. WebWork encapsulation is not set, so it leads to the Cos of the garbled problem, of course, if you use the Cos alone, you will avoid such problems.

3. Project actual deployment and use

• Configuration Files

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 "/>//webwok upload required to intercept stack
</action>
//intercept stack definition
<interceptor-stack name=" Fileuploadstack ">
<interceptor-ref name=" FileUpload "/> <interceptor-ref name= 
" params "/>
</interceptor-stack>
//intercept stack corresponding interceptor
<interceptor name= "FileUpload" 
class= " Com.opensymphony.webwork.interceptor.FileUploadInterceptor "/>
<interceptor name=" params " 

• Front-end use of more stable, more powerful ajaxupload here is not much to say, there are official web site: jQuery ajaxupload upload Image code

• Through the WebWork upload request encapsulation and parsing class, all the foreplay is ready, upload the Interceptor specifically implemented 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 a multimedia request, log it if it is, and execute the Action.
• Then determine if Multipartrequestwrapper contains errors in the file upload process, returns the error message to the client, and does not continue to invoke the Action.
• If none of the above judgment conditions are in place, begin traversing the parameters of the upload file in Multipartrequestwrapper and place the file name and file content type in the action parameter map for subsequent business classes.
• In WebWork's FileUpload Interceptor feature, the file it provides is a temporary file that is automatically deleted after the action is executed, and you must handle the file storage problem yourself in the action, or write to a directory on the server, or save it to a database. If you're going to write to a directory on the server, you'll have to deal with the same name as the file, but in fact the COS package already provides an automatic renaming rule with duplicate files.

Through the above code to introduce you to the WebWork implementation of file upload and download the relevant knowledge, hope 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.