2016-11-30 111 views
-2

我想上傳的UIView(圖),但我在郵件接收空圖片(來自Web服務)... Android是工作上傳的UIImage base64編碼

UIGraphicsBeginImageContext(self.view.bounds.size); 
    self.view.layer.render(in: UIGraphicsGetCurrentContext()!) 
    let screenShot = UIGraphicsGetImageFromCurrentImageContext(); 
    UIGraphicsEndImageContext(); 
    let jpegCompressionQuality: CGFloat = 1 
    let imgData:Data = UIImageJPEGRepresentation(screenShot!,jpegCompressionQuality)! 
    let lengthOfData = imgData.count 
    let strBase64 = imgData.base64EncodedString(options: []) 
    var request = URLRequest(url: URL(string: "http://myws.com/Chart.php")!) 
     request.httpMethod = "POST" 
    let postString = "data=\(strBase64)&[email protected]" 
    request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") 
    request.addValue("\(lengthOfData)", forHTTPHeaderField: "Content-Length") 
    request.httpBody = postString.data(using: String.Encoding.utf8) 
    let task = URLSession.shared.dataTask(with: request) { data, response, error in 
     guard let data = data, error == nil else { 
      print("error=\(error)") 
      return 
     } 
     if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { 
      print("statusCode \(httpStatus.statusCode)") 
      print("response = \(response)") 
     } 
     let responseString = String(data: data, encoding: .utf8) 
     print("responseString = \(responseString)") 
    } 
    task.resume() 
+0

我認爲你在這裏錯過了一些東西,如爲httpheaderfield設置值等 – KrishnaCA

回答

0

你的代碼採取的iOS的屏幕截圖設備很好。我想上傳的UIImage到服務器的POST請求缺乏以下的事情:

let imgData:NSData = data   
let lengthOfData = imgData.length 
// ENCODINGDATA - whatever encoding your server wants here 
request.addValue(ENCODINGDATA, forHTTPHeaderField: "Content-Type") 
request.addValue("\(lengthOfData)", forHTTPHeaderField: "Content-Length") 

除此之外,最好使用AlamoFire來處理這種複雜的服務器任務。它使它更容易。它可以這樣做

let imageData = UIPNGRepresentation(image)! 

Alamofire.upload(imageData, to: "https://httpbin.org/post").responseJSON { response in 

    debugPrint(response) 
} 

隨意建議編輯,使其更好。請讓我知道如果我的回答中有任何錯誤或缺點

+0

不起作用,我修改了你的建議代碼 – user1801745

+0

是你的形象在服務器接收仍然空? – KrishnaCA

+0

是的,使用'UIImageWriteToSavedPhotosAlbum(screenShot!,nil,nil,nil)'圖像正確地存儲到手機存儲器 – user1801745