2017-01-19 48 views
0

我想用api將客戶簽名圖像發佈到amazon s3 bucket_type服務器...我指的是不同的教程...我沒有從任何教程中獲得足夠的信息...我嘗試使用以下代碼但我得到零結果...如何將圖像上傳到swift3中的亞馬遜桶?

funcUpload(service:String,imagedata:Data,completion:@escaping (_ result:NSDictionary?,_ error:AnyObject?) ->()){   
let boundaryConstant = "----------V2y2HFg03eptjbaKO0j1" 
    let urlpath:String = "http:myurl" + service   
    let url:NSURL = NSURL(string:urlpath)! 
    let request = NSMutableURLRequest(url: url as URL) 
    request.httpMethod = "P0ST" 
    request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringLocalCacheData 

    request.httpShouldHandleCookies = false 
    let contentType = "multipart/form-data; boundary=\(boundaryConstant)"   
    request.setValue(contentType, forHTTPHeaderField: "Content-Type" 
    let body = NSMutableData() 
    if imagedata != nil{ 
     body.append("--\(boundaryConstant)\r\n".data(using: String.Encoding.utf8)!)   
     body.append("Content-Disposition: form-data; name=\"\("universalapparealproduct")\" ; filename=\"image.jpg\"\r\n".data(using: String.Encoding.utf8)!) 
     body.append("Content-Type: \("universalapparealproduct")\r\n\r\n".data(using: String.Encoding.utf8)!) 
     body.append(imagedata) 
     body.append("\r\n".data(using: String.Encoding.utf8)!)   
     } 
     body.append("--\(boundaryConstant)--\r\n".data(using:  String.Encoding.utf8)!) 
     request.httpBody = body as Data  
     let config = URLSessionConfiguration.ephemeral 
     self.session = URLSession(configuration: config) 
     let task = session.dataTask(with: request as URLRequest) {  (data, response, error) -> Void in 
     if let receivedData = data 
     {      
     do 
     {let resultDic = try JSONSerialization.jsonObject(with: receivedData, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary 
      completion(resultDic!,nil) 
     } 
     catch let error 
     { 
      NSLog("\(error)") 
     } 
    } 
    else if let errorMessage = error 
    { 
     completion(nil,errorMessage as AnyObject?) 
    } 
      self.session.invalidateAndCancel() 
    }   
    task.resume() 
    } 
} 

請任何人都可以幫我解決這個問題。 在此先感謝。

回答

0
  1. let urlpath:String = "http:myurl" + service看起來像一個錯字。
  2. 我假定服務變量包含一個帶有預先簽名憑據的URL,您可以上傳到該URL。確保這是正確的。如果沒有,則必須有服務器爲您提供預簽名證書。
  3. 使用PUTPOST
  4. 我希望該請求的身體也只是爲imageData,但你似乎是加入了很多的東西身上。我不知道你想上傳什麼樣的文件,但你正在製作一個奇怪的文件。如果這是你的意圖是好的,但只是我們意識到這是你在做什麼。如果要上傳自定義文件類型的縮進,我會將所有代碼移動到不同的函數中,然後使用另一個函數來上傳數據。
  5. 您必須設置的唯一HTTPHeader字段是Content-Length。它必須設置爲您發送的身體的大小。
  6. 請求的預期結果是長度爲0且沒有錯誤的數據。所以你的JSONSerialization在響應塊中是錯誤的。
+0

hi..my url我正在使用我的應用程序的URL與服務作爲文件/ upoad和後端他們只使用「POST」方法 –

+0

請求的主體是選擇圖像和bucket_type =「我的項目類型」所以我不明白我必須在請求正文中設置此bucket_type的位置 –

+0

將圖像上傳到S3的常用方法是從後端服務器獲取預先登記的URL。此網址已包含存儲區和文件名以及您需要上傳的所有權限。使用這個url你可以直接上傳到s3而不需要通過你的後端去看http://docs.aws.amazon.com/AmazonS3/latest/dev/PresignedUrlUploadObject.html。如果這是你正在使用的那麼你應該遵循我給的指示。如果你將圖像上傳到你的服務器,而服務器又將它上傳到S3,那麼我不能幫你,因爲我不知道該服務器希望接收什麼。 –

相關問題