2016-07-22 100 views
0

我從相機捕獲圖像並將圖像轉換爲base64格式。將圖像發送到服務器需要更多時間。如果沒有互聯網連接,我將它存儲到本地數據庫,一旦我獲得互聯網連接,我想發送多個圖像到服務器。從應用程序發送圖像到服務器的最佳方式是什麼?將圖像從iOS應用程序發送到服務器的正確方法

+0

通過base64發送圖像是不可取的,它需要很多時間才能上傳。使用Multipart進行上傳。通過此鏈接http://stackoverflow.com/questions/29623187/upload-image-with-multipart-form-data-ios-in-swift – Madhu

+0

您可以使用多部分格式發送圖像。 –

回答

-1

您可以爲多要求如下,然後用你的NSURLSession

NSString *boundary = [NSString stringWithFormat:@"Boundary-%@", [[NSUUID UUID] UUIDString]]; 

     // configure the request 
    NSString *urlString = YOUR_URL; 
    NSURL *url =[NSURL URLWithString:urlString]; 
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url]; 
    [request setHTTPMethod:@"POST"]; 
    // set content type 
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary]; 
    [request setValue:contentType forHTTPHeaderField: @"Content-Type"]; 

    //create body 
    request.HTTPBody = [self createBodyWithParameters:params paths:@[filePath] fieldName:fieldName boundary:boundary]; //params(NSDictionary) WILL BE YOUR PARAMETERS TO WEB SERVICE 

    [request setValue:[NSString stringWithFormat:@"%lu",(long)[request.HTTPBody length]] forHTTPHeaderField:@"Content-Lenght"]; 
+0

此問題標記爲「swift」。你的解決方案可能有價值,但不是用OP所要求的語言編寫的,所以它是無關緊要的。請在Swift中提供答案。謝謝。 – Moritz

1

這一要求你有沒有試過Alamofire?它支持文件上傳。

下面是圖像負載的例子:

public func requestImage(url: String) -> SignalProducer<UIImage, NetworkError> { 
     return SignalProducer { observer, disposable in 
      let serializer = Alamofire.Request.dataResponseSerializer() 
      Alamofire.request(.GET, url) 
       .response(queue: self.queue, responseSerializer: serializer) { 
        response in 
        switch response.result { 
        case .Success(let data): 
         guard let image = UIImage(data: data) else { 
          observer.sendFailed(.IncorrectDataReturned) 
          return 
         } 
         observer.sendNext(image) 
         observer.sendCompleted() 
        case .Failure(let error): 
         observer.sendFailed(NetworkError(error: error)) 
        } 
      } 
     } 
    } 

而這一次的例子爲async image load

相關問題