您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 文件上傳:ASIFormDataRequest 的表單實現

編輯:iOS 開發綜合

上傳文件在本質上是一次帶請求體的 POST。ASIHTTPRequest 提供的 ASIFormDataRequest 把 multipart 表單的拼裝細節封裝了起來,幾行代碼就能把圖片送出去。

頭文件

#import <UIKit/UIKit.h>
#import "ASIHTTPRequest.h"

@interface ios23_uploadViewController : UIViewController <ASIHTTPRequestDelegate>

- (IBAction)upload;

@end

實現文件

#import "ios23_uploadViewController.h"
#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"

@implementation ios23_uploadViewController

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

#pragma mark - View lifecycle

- (void)upload
{
    NSString *uploadURL = @"https://172.22.65.2/2012/upload.php";

    UIImage *im = [UIImage imageNamed:@"csdn"];
    NSData *data = UIImagePNGRepresentation(im);
    /*
     * iOS 取得圖片數據有兩種方式:UIImageJPEGRepresentation 與
     * UIImagePNGRepresentation。前者體積明顯小於後者,且可通過
     * 第二個參數控制壓縮質量,上傳場景更推薦使用 JPEG。
     */

    NSURL *url = [NSURL URLWithString:uploadURL];

    ASIFormDataRequest *aRequest = [[ASIFormDataRequest alloc] initWithURL:url];
    [aRequest setDelegate:self];
    [aRequest setRequestMethod:@"POST"];
    [aRequest addData:data
           withFileName:@"test.png"
         andContentType:@"image/png"
                forKey:@"file"];
    [aRequest addRequestHeader:@"Content-Type" value:@"binary/octet-stream"];
    // 該 value 需與服務端約定一致

    [aRequest setDidFinishSelector:@selector(headPortraitSuccess)];
    [aRequest setDidFailSelector:@selector(headPortraitFail)];

    [aRequest startAsynchronous];
}

- (void)headPortraitSuccess
{
    NSLog(@"上傳成功!");
}

- (void)headPortraitFail
{
    NSLog(@"上傳失敗!");
}

- (void)requestStarted:(ASIHTTPRequest *)request
{
    NSLog(@"開始請求!");
}

@end

幾個實戰要點

第一,setDidFinishSelector: 與 setDidFailSelector: 必須在 startAsynchronous 之前設置,順序顛倒會導致回調永遠不觸發。

第二,圖片格式選擇直接影響流量。UIImageJPEGRepresentation(image, 0.5) 通常能把體積壓到 PNG 的三分之一,頭像類業務幾乎看不出質量差異。

第三,Content-Type 的取值需與後端約定一致,常見寫法是 application/octet-stream 或按實際 MIME 類型填寫,兩端不一致會出現「請求成功但文件損壞」的現象。

第四,ASIHTTPRequest 早已停止維護,新項目請改用 NSURLSessionUploadTask 或 AFNetworking 的 uploadTaskWithRequest:。後者寫法如下:

NSMutableURLRequest *request =
    [httpClient.requestSerializer multipartFormRequestWithMethod:@"POST"
                                                       URLString:uploadURL
                                                      parameters:nil
                                       constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [formData appendPartWithFileData:data
                                    name:@"file"
                                fileName:@"test.png"
                                mimeType:@"image/png"];
    }];

NSURLSessionUploadTask *task =
    [httpClient uploadTaskWithRequest:request
                     fromFile:nil
                     progress:nil
                     completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        NSLog(error ? @"上傳失敗" : @"上傳成功");
    }];
[task resume];

此外,示例中的 URL 是明文 HTTP,iOS 9 之後 ATS 會直接攔截,需要在 Info.plist 中配置例外或改用 HTTPS。真實項目還應加上上傳進度回調與弱網重試策略。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved