ASIHTTPRequest系列(三):文件上傳

5、文件上傳html

一、服務端java

文件上傳須要服務端的配合。咱們可在本機搭建tomcat測試環境。關於tomcat在MacOSX下的安裝配置,參考做者另外一博文《安裝Tomcat到Mac OSX》。web

打開Eclipse,新建web工程。在其中新建一個ServletUploadServlet:apache

import java.io.*;數組

import java.util.*;緩存

 

importjavax.servlet.ServletException;tomcat

importjavax.servlet.http.HttpServlet;iphone

importjavax.servlet.http.HttpServletRequest;jsp

importjavax.servlet.http.HttpServletResponse;ide

 

importorg.apache.commons.fileupload.FileItem;

importorg.apache.commons.fileupload.disk.DiskFileItemFactory;

importorg.apache.commons.fileupload.servlet.ServletFileUpload;

 

public class UploadServletextends HttpServlet {

   

   private boolean isMultipart;

   private String filePath,title;

   private int maxFileSize = 500 * 1024;

   private int maxMemSize = 4 * 1024;

   private File file ;

 

   public void init( ){

     // web.xmlcontext_param中得到上傳文件目錄(/data.

     filePath = 

            getServletContext().getInitParameter("file-upload"); 

   }

   public voiddoPost(HttpServletRequest request, 

              HttpServletResponse response)

              throws ServletException,java.io.IOException {

   

     // 檢查表單是否帶有 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("<head>");

         out.println("<title>Servlet upload</title>");  

         out.println("</head>");

         out.println("<body>");

         out.println("<p>No file uploaded</p>"); 

         out.println("</body>");

         out.println("</html>");

         return;

     }

      DiskFileItemFactoryfactory = new DiskFileItemFactory();

     // 內存最大可緩存尺寸

      factory.setSizeThreshold(maxMemSize);

     // 指定當數據超過內存最大可緩存尺寸時,臨時文件的目錄

      factory.setRepository(new File(filePath+"temp"));

 

     // 文件上傳對象

     ServletFileUpload upload = new ServletFileUpload(factory);

     // 設置文件上傳最大容許尺寸

      upload.setSizeMax( maxFileSize );

 

      try

     out.println("<%@pagecontentType='text/html; charset=GBK'%>");

     out.println("<html>");

     out.println("<head>");

     out.println("<title>Servletupload</title>");  

     out.println("</head>");

     out.println("<body>");

     // 獲取multipart/form-data內容,其中每一個field被分紅不一樣part

     List fileItems = upload.parseRequest(request);

     // 枚舉每一個field

     Iterator i = fileItems.iterator();

     while ( i.hasNext () ) 

     {

         FileItem fi = (FileItem)i.next();

         if ( !fi.isFormField() ) // 若是fieldFile

         {

            // 獲取fieldnameid

           String fieldName = fi.getFieldName();

           String fileName = fi.getName();

            // 文件名中文處理

           fileName=newString(fileName.getBytes(),"gbk");

           out.println("file name:"+fileName+"<br>");

           String contentType = fi.getContentType();

            boolean isInMemory= fi.isInMemory();

            long sizeInBytes= fi.getSize();

            // 把上傳數據寫入本地磁盤

           if(fileName.lastIndexOf("//") >= 0 ){

              file = new File( filePath + 

              fileName.substring( fileName.lastIndexOf("//"))) ;

           }else{

              file = new File( filePath + 

              fileName.substring(fileName.lastIndexOf("//")+1)) ;

           }

           fi.write( file ) ;

           out.println("Uploaded Filename:" + fileName + "<br>");

         }else{// 若是fieldForm Field

         title=fi.getFieldName();

         if(title.equals("title")){

         title=new String(fi.get(),"gbk");

         out.println("title:"+title+"<br>");

         }

         }

     }

      out.println("</body>");

     out.println("</html>");

   }catch(Exception ex) {

       System.out.println(ex);

   }

   }

   public voiddoGet(HttpServletRequest request, 

                      HttpServletResponse response)

        throws ServletException,java.io.IOException {

        

        throw new ServletException("GET method used with " +

               getClass( ).getName( )+": POSTmethod required.");

   } 

}

再新建一個upload.jsp頁面做爲測試:

<%@page contentType="text/html; charset=GBK" language="java"import="java.util.*"%>

<html>

<head>

<title>fbysss UploadBean 示例</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="請選擇文件">

<p>附件</p>

<p> <input name="attach" type="FILE"id="attach" size="50"> </p>

<input name="ok" type"submit"value="提交">

</form>

</html>

 

將工程部署到tomcat中,啓動tomcat,訪問http://localhost:8080/test/upload.jsp,顯示界面以下:

 

選擇一個文件進行上傳,而後到/data目錄下檢查該文件是否上傳成功。

二、iPhone客戶端

新建類,選擇UIViewController subclass,並勾上「WithXIB for user interface」,命名爲 UploadViewController。

用 IB 打開 Xib 文件,在其中拖入1個 UIToolBar 、1個UIBarButtonItem 和1個 UIWebView、1個UIProgressView:

 

在Xcode中聲明必要的變量和 IBOutlet/IBAction:

#import <UIKit/UIKit.h>

#import "ASIFormDataRequest.h"

#import "ASIHTTPRequest.h"

 

@interface  UploadViewController : UIViewController {

UIBarItembutton;

UIWebViewwebView;

UIProgressViewprogress;

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

 

將全部出口正確地鏈接到 UpdateController.xib 中,保存。

打開MainWindow.xib,拖一個UIViewController進去並將其Identifier改成UpdateController,再將它鏈接到Window對象的的rootViewController。

編寫 UIButton 的 Touch up inside 事件代碼以下:

-(IBAction)go{

NSString* s=@"哈哈哈";

url=[NSURL URLWithString:@"http://localhost:8080/test/UploadServlet"];

request = [ASIFormDataRequest requestWithURL:url];

// 字符串使用 GBK 編碼,由於 servlet 只識別GBK

NSStringEncoding enc=CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingMacChineseSimp);

[request setStringEncoding:enc];

[self printBytes:s encoding:enc];// 打印GBK編碼字符

[request setPostValue:s forKey:@"title"];

[request setFile:@"/Users/kmyhy/Documents/iphone/Iphone開發介紹.doc" forKey:@"attach"];

[request setDelegate:self];

[request setDidFinishSelector:@selector(responseComplete)];

[request setDidFailSelector:@selector(responseFailed)];

[button setEnabled:NO];

[request startSynchronous];

}

-(void)responseComplete{

// 請求響應結束,返回responseString

NSString*responseString = [request responseString];

[webView loadHTMLString:responseStringbaseURL:url];

[button setEnabled:YES];

 

}

-(void)respnoseFailed{

//請求響應失敗,返回錯誤信息

NSError *error = [request error];

[webView loadHTMLString:[error descriptionbaseURL:url];

[button setEnabled:YES];

}

-(void)printBytes:(NSString *)strencoding:(NSStringEncoding)enc{

NSLog(@"defaultCStringEncoding:%d",[NSString defaultCStringEncoding]);

// 根據給定的字符編碼,打印出編碼後的字符數組

const char *bytes=[str cStringUsingEncoding:enc];

for (int i=0;i<strlen(bytes);i++){

NSLog(@"%d%X",(i+1),bytes[i]);

}

}

 

編譯、運行。點擊go按鈕,程序運行效果以下:

相關文章
相關標籤/搜索