V. File Upload
1. Server
File Upload requires the cooperation of the server. We can build a tomcat test environment on the local machine. For the installation and configuration of tomcat in Mac OSX, refer to the author's blog "install Tomcat to Mac OSX".
Open eclipse and create a web project. Create a servlet uploadservlet:
ImportJava. Io .*;
ImportJava. util .*;
ImportJavax. servlet. servletexception;
ImportJavax. servlet. http. httpservlet;
ImportJavax. servlet. http. httpservletrequest;
ImportJavax. servlet. http. httpservletresponse;
ImportOrg. Apache. commons. fileupload. fileitem;
ImportOrg. Apache. commons. fileupload. disk. diskfileitemfactory;
ImportOrg. Apache. commons. fileupload. servlet. servletfileupload;
Public classUploadservletExtendsHttpservlet {
Private BooleanIsmultipart;
PrivateString filepath, title;
Private intMaxfilesize = 500*1024;
Private intMaxmemsize = 4*1024;
PrivateFile file;
Public voidInit (){
// Obtain the Upload File directory (/data) from context_param of Web. xml ).
Filepath =
Getservletcontext (). getinitparameter ("file-upload ");
}
Public voidDopost (httpservletrequest request,
Httpservletresponse response)
ThrowsServletexception, java. Io. ioexception {
// Check whether the form has enctype = "multipart/form-Data"
Ismultipart = servletfileupload.Ismultipartcontent(Request );
Response. setcontenttype ("text/html ");
Response. setcharacterencoding ("GBK ");
Java. Io. printwriter out = response. getwriter ();
If(! Ismultipart ){
Out. println ("<HTML> ");
Out. println ("
Out. println ("<title> servlet upload </title> ");
Out. println ("
Out. println ("<body> ");
Out. println ("<p> NO File Uploaded </P> ");
Out. println ("</body> ");
Out. println ("
Return;
}
Diskfileitemfactory factory =NewDiskfileitemfactory ();
// Maximum Cache size of memory
Factory. setsizethreshold (maxmemsize );
// Specify the directory of the temporary file when the data exceeds the maximum cache size in the memory
Factory. setrepository (NewFile (filepath + "Temp "));
// Object to be uploaded
Servletfileupload upload =NewServletfileupload (factory );
// Sets the maximum size allowed for file upload.
Upload. setsizemax (maxfilesize );
Try{
Out. println ("<% @ page contenttype = 'text/html; charset = GBK '%> ");
Out. println ("<HTML> ");
Out. println ("
Out. println ("<title> servlet upload </title> ");
Out. println ("
Out. println ("<body> ");
// Obtain the multipart/form-data content. Each field is divided into different parts.
List fileitems = upload. parserequest (request );
// Enumerate each field
Iterator I = fileitems. iterator ();
While(I. hasnext ())
{
Fileitem Fi = (fileitem) I. Next ();
If(! Fi. isformfield () // If field is File
{
// Obtain the field name or ID
String fieldname = Fi. getfieldname ();
String filename = Fi. getname ();
// Process Chinese characters of file names
Filename =NewString (filename. getbytes (), "GBK ");
Out. println ("file name:" + filename + "<br> ");
String contenttype = Fi. getcontenttype ();
BooleanIsinmemory = Fi. isinmemory ();
LongSizeinbytes = Fi. getsize ();
// Write the uploaded data to the local disk
If(Filename. lastindexof ("//")> = 0 ){
File =NewFile (filepath +
Filename. substring (filename. lastindexof ("//")));
}Else{
File =NewFile (filepath +
Filename. substring (filename. lastindexof ("//") + 1 ));
}
Fi. Write (File );
Out. println ("uploaded filename:" + filename + "<br> ");
}Else{// If field is form field
Title = Fi. getfieldname ();
If(Title. Equals ("title ")){
Title =NewString (Fi. Get (), "GBK ");
Out. println ("title:" + title + "<br> ");
}
}
}
Out. println ("</body> ");
Out. println ("
}Catch(Exception ex ){
System.Out. Println (Ex );
}
}
Public voidDoget (httpservletrequest request,
Httpservletresponse response)
ThrowsServletexception, java. Io. ioexception {
Throw newServletexception ("Get method used with" +
Getclass (). getname () + ": POST method required .");
}
}
Create an upload. jsp page as a test:
<% @ Page contenttype ="Text/html; charset = GBK"Language ="Java"
Import ="Java. util .*"%>
<HTML>
<Head>
<Title> fbysss uploadbean example </title>
<! -- Meta http-equiv = "Content-Type" content = "text/html; charset = iso-8859-1" -->
<! -- Meta http-equiv = "Content-Type" content = "text/html; charset = gb2312" -->
</Head>
<Form name ="Form1"Method ="Post"Action ="Uploadservlet"
Enctype ="Multipart/form-Data">
<Input name ="Title"Type ="Text"Value ="Select file"
>
<P> attachment </P>
<P> <input name ="Attach"Type ="File"Id ="Attach"
Size ="50"> </P>
<Input name ="OK"Type ="Submit"Value ="Submit"
>
</Form>
</Html>
Deploy the project to Tomcat, start Tomcat, and access http: // localhost: 8080/test/upload. jsp
, The display interface is as follows:
Select a file for upload and go to the/data directory to check whether the file has been uploaded successfully.
2. iPhone Client
Create a class, select uiviewcontroller subclass, and check "with XIB for user interface" and name it uploadviewcontroller.
Open the XIB file with IB, drag one uitoolbar, one uibarbuttonitem, one uiwebview, and one uiprogressview in it:
Declare necessary variables and iboutlet/ibaction in xcode:
# Import <uikit/uikit. h>
# Import "asiformdatarequest. H"
# Import "asihttprequest. H"
@ Interface uploadviewcontroller: uiviewcontroller {
Uibaritem * button;
Uiwebview * webview;
Uiprogressview * progress;
Asiformdatarequest * request;
Nsurl * URL;
}
@ Property (retain, nonatomic) iboutlet uibaritem * button;
@ Property (retain, nonatomic) iboutlet uiprogressview * progress;
@ Property (retain, nonatomic) iboutlet uiwebview * webview;
-(Ibaction) go;
-(Void) printbytes :( nsstring *) STR encoding :( nsstringencoding) ENC;
@ End
Connect all exits to updatecontroller. XIB correctly and save the settings.
Open mainwindow. XIB, drag a uiviewcontroller, change its identifier to updatecontroller, and connect it to the rootviewcontroller of the window object.
The code for writing the uibutton touch up inside event is as follows:
-(Ibaction) go {
Nsstring * s = @ "HAHAHA ";
Url = [nsurl urlwithstring: @ "http: // localhost: 8080/test/uploadservlet"];
Request = [asiformdatarequest requestwithurl: url];
// The string is encoded in GBK, because the servlet only recognizes GBK
Nsstringencoding ENC = cfstringconvertencodingtonsstringencoding (kcfstringencodingmacchinesesimp );
[Request setstringencoding: ENC];
[Self printbytes: s encoding: ENC]; // print GBK encoded characters
[Request setpostvalue: s forkey: @ "title"];
[Request setfile: @ "/users/kmyhy/documents/iPhone development overview. Doc" forkey: @ "Attach"];
[Request setdelegate: Self];
[Request setdidfinishselector: @ selector (responsecomplete)];
[Request setdidfailselector: @ selector (responsefailed)];
[Button setenabled: No];
[Request startsynchronous];
}
-(Void) responsecomplete {
// When the request response ends, responsestring is returned.
Nsstring * responsestring = [Request responsestring];
[Webview loadhtmlstring: responsestring baseurl: url];
[Button setenabled: Yes];
}
-(Void) respnosefailed {
// If the request response fails, an error message is returned.
Nserror * error = [Request Error];
[Webview loadhtmlstring: [error description] baseurl: url];
[Button setenabled: Yes];
}
-(Void) printbytes :( nsstring *) STR encoding :( nsstringencoding) ENC {
Nslog (@ "defaultcstringencoding: % d", [nsstring defaultcstringencoding]);
// Print the encoded character array based on the given character encoding
Const char * bytes = [STR cstringusingencoding: ENC];
For (INT I = 0; I <strlen (bytes); I ++ ){
Nslog (@ "% d % x", (I + 1), bytes [I]);
}
}
Compile and run. Click Go. The program running effect is as follows: