溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

使用post方法上傳文件的兩種做法

發(fā)布時間:2020-07-24 16:10:37 來源:網(wǎng)絡(luò) 閱讀:1061 作者:wcrane 欄目:開發(fā)技術(shù)


項目需要使用HTTP協(xié)議中的POST方法上傳文件,稍微總結(jié)了一下,將過程貼出來,方便以后參考。有兩種方法,第一是使用NSMutableURLRequest完全從零開始設(shè)置,可以加深對HTTP協(xié)議的理解;第二種是直接使用別人封裝好的代碼,如AFNetworking。

方法一,從0開始文件上傳
NSURL *url = [NSURL URLWithString:@"http://yo.diveinedu.com/upload.php"];NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];request.HTTPMethod = @"POST";//0. 設(shè)置分隔符NSString *boundary = @"a1b2c3d4e5f6";[request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary] forHTTPHeaderField:@"Content-Type"];NSLog(@"%@", request.allHTTPHeaderFields);NSMutableData *httpBody = [NSMutableData data];//1. 開始的分隔符[httpBody appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];//2. 設(shè)置內(nèi)容: 標簽名,文件名等[httpBody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"fileToUpload\"; filename=\"%@\"\r\n", @"mask0.png"] dataUsingEncoding:NSUTF8StringEncoding]];NSString *path = [[NSBundle mainBundle] pathForResource:@"mask0" ofType:@"png"];NSLog(@"%@", [self typeForPath:path]);//3. 設(shè)置內(nèi)容格式[httpBody appendData:[[NSString stringWithFormat:@"Content-Type: %@\r\n\r\n", [self typeForPath:path]] dataUsingEncoding:NSUTF8StringEncoding]];NSString *body = [[NSString alloc] initWithData:httpBody encoding:NSUTF8StringEncoding];NSLog(@"%@", body);//4. 添加真正的內(nèi)容NSData *data = [NSData dataWithContentsOfFile:path];[httpBody appendData:data];//5. 添加結(jié)束邊界[httpBody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];//6. 設(shè)置http bodyrequest.HTTPBody = httpBody;//7. 發(fā)送請求[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
    NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"%@", str);}];

重點:

  1. 注意協(xié)議中需要使用回車換行(\r\n)的位置,HTTP是一個基于文本行的協(xié)議,通過回車換行來控制格式。

  2. 注意分隔符(Boundary)的設(shè)置,尤其是(--)的增加。

設(shè)置后的內(nèi)容應(yīng)該是下面的樣子(為了看得更清楚,將回車換行用文字表示出來了):

POST /upload.php HTTP/1.1\r\nHost: yo.diveinedu.com\r\nContent-Type: multipart/form-data; boundary=abcdefghigk\r\n\r\nContent-Disposition: form-data; name="fileToUpload"; filename="mask0.png"\r\nContent-Type: p_w_picpath/png\r\n\r\n--abcdefghigk\r\n圖片數(shù)據(jù)\r\n--abcdefghigk--\r\n
方法二,使用AFNetworking中的方法
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];manager.responseSerializer = [AFHTTPResponseSerializer serializer];[manager POST:@"http://yo.diveinedu.com/upload.php" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
    //1. 方法一//        NSError *error;//        if (![formData appendPartWithFileURL:[NSURL fileURLWithPath:path] name:@"fileToUpload" fileName:[path lastPathComponent] mimeType:@"p_w_picpath/png" error:&error]) {//            NSLog(@"error appending part: %@", error);//        }

    //2. 方法二
    NSData *data = [NSData dataWithContentsOfFile:path];
    [formData appendPartWithFileData:data name:@"fileToUpload" fileName:[path lastPathComponent] mimeType:@"p_w_picpath/png"];} success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSData *data = (NSData *)responseObject;
    NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"%@", str);} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"%@", error);}];

進行網(wǎng)絡(luò)編程的時候,可以使用Wireshark之類的抓包工具輔助調(diào)試??梢院苊鞔_的看到發(fā)送或接收的數(shù)據(jù)是否正確。

最后祝大家兒童節(jié)快樂~~~

http://io.diveinedu.com

http://www.diveinedu.com

http://bbs.diveinedu.com

https://github.com/DiveinEdu-CN


向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI