2017-02-02 136 views
4

我目前正試圖上傳一個圖像到亞馬遜與預先簽名的網址。Alamofire圖像上傳與PUT

它的工作方式是,我發出一個GET請求來獲取預先簽名的URL,而不是使用從GET請求返回的url上傳圖片的PUT請求。

這兩個規則是:Content-Type需要是image \ jpeg,並且http方法必須是PUT。

因此,目前我的上傳代碼返回200,但亞馬遜拒絕數據。

這裏是我的代碼:

爲上載的實際URL返回是:https://mimik-apps-channel.s3-us-west-2.amazonaws.com/profiles/2312528782074206653.jpg?X-Amz-Expires=3600&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAJ36SCZW7WGBAW7CQ/20170202/us-west-2/s3/aws4_request&X-Amz-Date=20170202T102202Z&X-Amz-SignedHeaders=host&X-Amz-Signature=007ad8694fe1ed83b08d4890f17b9985e169f7ab8fcd7b0d648a383c69ebc748

    var headers = Alamofire.SessionManager.defaultHTTPHeaders 
        headers["Content-Type"] = "image/jpeg" 
        let URL = try! URLRequest(url: url, method: .put, headers: headers) 

        Alamofire.upload(multipartFormData: { (multipartFormData) in 
         let compressionQuality: CGFloat = 0.8 
         guard let imageData = UIImageJPEGRepresentation(image, compressionQuality) else { 
          print("Unable to get JPEG representation for image \(image)") 

          return 
         } 

         multipartFormData.append(imageData, withName: "image.jpg", mimeType: "image/jpeg") 
         // code 
        }, with: URL, encodingCompletion: { (result) in 
         switch result { 
         case .success(let upload, _, _): 
          upload.responseJSON { response in 
           print("SUCCESS -> \(response.request?.allHTTPHeaderFields)") 

          } 

         case .failure(let encodingError): 
          print(encodingError) 
         } 
        }) 

我懷疑,當我打印的HTTP標頭的Content-Type始終顯示的multipart/form-data的而不是我需要的image/jpeg,但是現在我失去了解決這個問題的方法。

回答

3

其實我最近有同樣的要求(除了我需要PNG代替JPG)。

以下是你如何去做。

let compressionQuality: CGFloat = 0.8 
guard let imageData = UIImageJPEGRepresentation(image, compressionQuality) else { 
    print("Unable to get JPEG representation for image \(image)") 
    return 
} 

let headers = [ 
    "Content-Type": "image/jpeg" 
] 

// presignedUrl is a String 

Alamofire.upload(imageData, to: presignedUrl, method: .put, headers: headers) 
    .responseData { 
     response in 

     guard let httpResponse = response.response else { 
      print("Something went wrong uploading") 
      return 
     } 

     let publicUrl = presignedUrl.components(separatedBy: "?")[0] 
    } 
1

您是否更改了允許後臺服務的功能?

enter image description here

一些工作對我說:

let imageData = UIImageJPEGRepresentation(image , 0.7) 

     Alamofire.upload(imageData!, to: url, method: .put, headers: nil).responseJSON(completionHandler: { (response) in 
       debugPrint(response) 
      })