iOS上傳映像到伺服器,以及伺服器PHP接收的幾種方法

來源:互聯網
上載者:User

1. 將圖片轉換為Base64編碼,POST上傳。PHP將Base64解碼為二進位,再寫出檔案。缺點:不能上傳較大的圖片

// iOS(Swift)func upload(image: UIImage, url: String) {    let imageData = UIImageJPEGRepresentation(image, 0.3) // 將圖片轉換成jpeg格式的NSData,壓縮到0.3    let imageStr = imageData?.base64EncodedStringWithOptions(.Encoding64CharacterLineLength) // 將圖片轉換為base64字串    let params: NSDictionary = ["file": imageStr!]    let manager = AFHTTPRequestOperationManager()    // 採用POST的方式上傳,因為POST對長度沒有限制    manager.POST(url, parameters: params, success: { (_: AFHTTPRequestOperation!, response: AnyObject!) in        // 成功    }) { (_: AFHTTPRequestOperation!, _: NSError!) in        // 失敗    }}
 

2.AFNetworking上傳,PHP端通過正常接收網頁上傳方法來接收圖片

static func uploadPortrait(image: UIImage, url: String) {    let manager = AFHTTPRequestOperationManager()    // fromData: AFN封裝好的http header類,可以添加請求體    manager.POST(url, parameters: [:], constructingBodyWithBlock: { (fromData: AFMultipartFormData!) in        let pngData = UIImagePNGRepresentation(image)        // name必須和後台PHP接收的參數名相同($_FILES["file"])        // fileName為圖片名        fromData.appendPartWithFileData(pngData, name: "file", fileName: "image.png", mimeType: "image/png")              // let jpegData = UIImageJPEGRepresentation(image, 0.3)        // fromData.appendPartWithFileData(jpegData, name: "file", fileName: "image.jpg", mimeType: "image/jpeg")    }, success: { (operation: AFHTTPRequestOperation!, response: AnyObject!) in        // 成功    }) { (operation: AFHTTPRequestOperation!, error: NSError!) in        // 失敗    }   }
 0) {        echo $_FILES["file"]["error"]; // 錯誤碼    } else {                   $fillname = $_FILES['file']['name']; // 得到檔案全名        $dotArray = explode('.', $fillname); // 以.分割字串,得到數組        $type = end($dotArray); // 得到最後一個元素:檔案尾碼        $path = "../portrait/".md5(uniqid(rand())).'.'.$type; // 產生隨機唯一的名字        move_uploaded_file( // 從臨時目錄複寫到目標目錄          $_FILES["file"]["tmp_name"], // 儲存在伺服器的檔案的臨時副本的名稱          $path);        echo "成功";    } } else {    echo "檔案類型不正確";}?>

3.將圖片封裝在Http的請求報文中的請求體(body)中上傳。也是AFN上傳的原理

// 使用OC封裝#import @interface RequestPostUploadHelper : NSObject+ (NSMutableURLRequest *)uploadImage:(NSString*)url uploadImage:(UIImage *)uploadImage params:(NSMutableDictionary *)params;@end#import "RequestPostUploadHelper.h"@implementation RequestPostUploadHelper+ (NSMutableURLRequest *)uploadImage:(NSString*)url uploadImage:(UIImage *)uploadImage params:(NSMutableDictionary *)params {    [params setObject:uploadImage forKey:@"file"];    //分界線的標識符    NSString *TWITTERFON_FORM_BOUNDARY = @"AaB03x";    //根據url初始化request    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]                                                           cachePolicy:NSURLRequestReloadIgnoringLocalCacheData                                                       timeoutInterval:10];    //分界線 --AaB03x    NSString *MPboundary=[[NSString alloc]initWithFormat:@"--%@",TWITTERFON_FORM_BOUNDARY];    //結束符 AaB03x--    NSString *endMPboundary=[[NSString alloc]initWithFormat:@"%@--",MPboundary];    //要上傳的圖片    UIImage *image=[params objectForKey:@"file"];    //得到圖片的data    NSData* data = UIImagePNGRepresentation(image);    //http body的字串    NSMutableString *body=[[NSMutableString alloc]init];    //參數的集合的所有key的集合    NSArray *keys= [params allKeys];    //遍曆keys    for(int i = 0; i < [keys count]; i++)    {        //得到當前key        NSString *key = [keys objectAtIndex:i];        //如果key不是file,說明value是字元類型,比如name:Boris        if(![key isEqualToString:@"file"])        {            //添加分界線,換行            [body appendFormat:@"%@\r\n",MPboundary];            //添加欄位名稱,換2行            [body appendFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",key];            //添加欄位的值            [body appendFormat:@"%@\r\n",[params objectForKey:key]];        }    }    ////添加分界線,換行    [body appendFormat:@"%@\r\n",MPboundary];    //聲明file欄位,檔案名稱為image.png    [body appendFormat:@"Content-Disposition: form-data; name=\"file\"; filename=\"image.png\"\r\n"];    //聲明上傳檔案的格式    [body appendFormat:@"Content-Type: image/png\r\n\r\n"];    //聲明結束符:--AaB03x--    NSString *end=[[NSString alloc] initWithFormat:@"\r\n%@",endMPboundary];    //聲明myRequestData,用來放入http body    NSMutableData *myRequestData = [NSMutableData data];    //將body字串轉化為UTF8格式的二進位    [myRequestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];    //將image的data加入    [myRequestData appendData:data];    //加入結束符--AaB03x--    [myRequestData appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];    //設定HTTPHeader中Content-Type的值    NSString *content=[[NSString alloc]initWithFormat:@"multipart/form-data; boundary=%@",TWITTERFON_FORM_BOUNDARY];    //設定HTTPHeader    [request setValue:content forHTTPHeaderField:@"Content-Type"];    //設定Content-Length    [request setValue:[NSString stringWithFormat:@"%d", [myRequestData length]] forHTTPHeaderField:@"Content-Length"];    //設定http body    [request setHTTPBody:myRequestData];    //http method    [request setHTTPMethod:@"POST"];    return request;}@end
// 使用// Swiftstatic func uploadPortrait(image: UIImage, url:String) {    // 使用    let request = RequestPostUploadHelper.uploadImage(url, uploadImage: image, params: [:])    // 非同步網路請求    NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue()) { (response: NSURLResponse?, data: NSData?, error: NSError?) in        if error != nil {            // 失敗        } else {            // 成功        }    }}
 

4.iOS圖片轉換為NSData,通過POST上傳。PHP接收POST參數,將NSData的16進位編碼轉換為PHP支援的二進位,再寫出檔案儲存

暫時沒有找到辦法,PHP接收到16進位編碼後,使用演算法轉換為二進位後無法輸出圖片

5.二進位POST上傳。PHP直接將資料儲存為圖片

暫時沒有找到辦法,iOS端使用NSData的getBytes無法轉換為二進位

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    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.