In struts2, you can use action to download files from inputstream and receive files on iOS and Android devices.

Source: Internet
Author: User
Tags file url

I recently encountered some file downloading problems in mobile development. After implementation, I made a special record for future reference.

The simplest way to download is to directly send the file URL on the network to the mobile phone, and then the mobile phone requests the file through the URL, there is a disadvantage in doing so that the requested user cannot be accurately verified. Another method is to use action to verify the user's identity before sending a file to the handheld device (requester ). The second method is implemented below.

 

    • The server side is very simple, that is, writing an xml configuration file and implementing a simple action.

The configuration file of Struts. XML is as follows:

 <  Result  Name  = "Download"  Type  = "Stream"  >  <  Param  Name  = "Contenttype" > Application/octet-stream </  Param  >  <  Param  Name  = "Inputname"  > Targetfile </  Param  >  <  Param  Name  = "Contentdisposition" > $ {Suffix} </  Param  >  <  Param  Name  = "Contentlength"  > $ {Filesize} </  Param  >  <  Param  Name  = "Buffersize" > 4096 </  Param  >  </  Result  > 

Note:

 
Contenttype: Specifies the file type. Application/octet-stream indicates all file types. view other file types;
 
Inputname: The inputstream stream of the file. The action must provide a gettargetfile () method that returns inputstream;

Contentdisposition: File Name of the downloaded object. $ {suffix} indicates the returned value of the getsuffix () method in the action. You can also place filename =$ {filename} here }, in this way, the browser will automatically find the file name and display it when accessing through the browser;
 
Contentlength: The size of the downloaded file. The method for obtaining the file is the same as above. The type is long.
Buffersize: Cache size

The implementation of the Action object is as follows:
 
/*** File output stream * @ return * @ throws exception */Public inputstream gettargetfile () throws exception {Java. io. file F = new Java. io. file ("D: \ test. avi "); If (F. exists () {return New fileinputstream (f);} else {return NULL ;}/ *** set the name of the returned file * @ return */Public String getfilename () {return "test. avi ";}/*** sets the size of the returned file * @ return */public long getfilesize () {Java. io. file F = new Java. io. file ("D: \ test. avi "); Return F. length ();}/*** executes the logic processing of the request, and then determines whether to return the file * @ return */Public String download () based on the result () {// perform authentication or other logic checks if (true) {return "Download";} return "error ";}
    • The mobile requester implementation is as follows:

IOS end

Network Access endCodeAs follows:

Nsurl * DownLoadURL = [nsurl urlwithstring: url]; nsmutableurlrequest * request = [nsmutableurlrequest requestwithurl: DownLoadURL]; optional * response = nil; nserror * error = nil; nsdata * resdata = [nsurlconnection sendsynchronousrequest: Request returningresponse: & response error: & error]; If (error) {nslog (@ "File Download request failed, error message: % @", error); Return nil;} If (resdata) {If (Response & [respondstoselector: @ selector (allheaderfields)])
{Nsdictionary * httpresponseheaderfields = [Response allheaderfields]; // obtain the corresponding header long size = [[httpresponseheaderfields objectforkey: @ "Content-Length"] longvalue]; // obtain the file size, which is the nsstring * filesuffix = [httpresponseheaderfields objectforkey: @ "content-disposition"] transmitted by the server in the corresponding header; // The suffix vsfileutil * fileutil = [[vsfileutil alloc] init] set on my server; // a custom file tool class nsstring * filepath = [fileutil writetofilewithnsdata: resdata filename: [fileid stringbyappendingformat :@". % @ ", filesuffix]; // create the file return filepath ;}}

The file tool class code is as follows:

Nsarray * dir = nssearchpathfordirectoriesindomains (nscachesdirectory, nsuserdomainmask, yes); // obtain the Library/caches Directory, which isProgramExit will not be cleared, and iTunes will not back up this directory nsstring * cdownloadbasefolderpath = [[dir objectatindex: 0] stringbyappendingpathcomponent: @ "fmadownload"]; // create the Library/caches/fmadownload directory as the download directory nsstring * filepath = [cdownloadbasefolderpath stringbyappendingpathcomponent: file]; // construct the absolute path nsfilemanager * fm = [nsfilemanager defaultmanager] based on the file name and path; // obtain the File Manager [FM removeitematpath: filepath error: Nil]; // if the object already exists, the object will be removed and no exception will be thrown if the object does not exist. to capture the prompt information, you can define an nserror parameter to pass to the error parameter if ([data writetofile: filepath atomically: Yes]) // write the content into the file by Atomic processing {return filepath;} else {return nil ;}

 

Android end

Because it is developed in Java, this process will become N times simpler than that on iOS. The specific code is as follows:

 

Public void download () throws exception {inputstream is = NULL; bufferedinputstream Bis = NULL; fileoutputstream Fos = NULL; bufferedoutputstream Bos = NULL; try {httpclient = new defaulthttpclient (New basichttpparams (); httppost httprequest = new httppost (validateurl); // The request address httpresponse response = httpclient.exe cute (httprequest ); header [] headers = response. getallheaders (); long size = 0 ;// File Size String suff = ""; // file suffix for (header H: headers) {If ("content-disposition ". equals (H. getname () {suff = H. getvalue (); log. I ("janken", suff);} else if ("Content-Length ". equals (H. getname () {size = long. valueof (H. getvalue (); log. I ("janken", size + "") ;}} if (response. getstatusline (). getstatuscode ()! = Httpstatus. SC _ OK) {Throw new exception ("request failed");} httpentity resentity = response. getentity (); is = resentity. getcontent (); // get the object input stream Bis = new bufferedinputstream (is); file newfile = new file ("/sdcard/test. "+ suff); Fos = new fileoutputstream (newfile); Bos = new bufferedoutputstream (FOS); byte [] bytes = new byte [4096]; int Len = 0; // The last time length may be less than 4096 while (LEN = bis. read (bytes)> 0) {Bos. write (bytes, 0, le N);} Bos. Flush ();} finally {If (Bis! = NULL) bis. Close (); If (Bos! = NULL) Bos. Close (); If (FOS! = NULL) FOS. Close (); httpclient. getconnectionmanager (). Shutdown ();}}

 

 

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.