将图像上传到服务器Swift 3



我正在尝试使用Swift 3将图像上传到iOS中的服务器,我尝试使用Alamofire,但它不起作用,因此我只是在此论坛中搜索了另一个解决方案但是没有运气。

我找到了一些答案,说问题可能是服务器端,但是,在Android上,图像正确上传了。

这是我在Swift 3中的上传功能:

func uploadImage(image: UIImage){
         let imageData = UIImageJPEGRepresentation(image, 0.1)!
         let session = URLSession(configuration: URLSessionConfiguration.default)
         guard let url = URL(string: uploadPicUrl) /* your API url */) else { return }
         var request = URLRequest(url: url)
         request.httpMethod = "POST"
         let boundary = "---------------------------14737809831466499882746641449"
         let contentType = "multipart/form-data; boundary=(boundary)"
         request.addValue(contentType, forHTTPHeaderField: "Content-Type")
         var body = Data()
         body.append("--(boundary)rn".data(using: String.Encoding.utf8)!)
         body.append("Content-Disposition: form-data; name="userfile"; filename="img.jpg"rn".data(using: String.Encoding.utf8)!)
         body.append("Content-Transfer-Encoding: binaryrnrn".data(using: String.Encoding.utf8)!)
         body.append(imageData)
         body.append("rn".data(using: String.Encoding.utf8)!)
         body.append("--(boundary)--rn".data(using: String.Encoding.utf8)!)
         request.httpBody = body
         print("request", request.debugDescription)
         print("body", body.debugDescription)
         let dataTask = session.dataTask(with: request) { (data, response, error) in
         if let error = error {
         print("Something went wrong: (error)")
         }
         if let response = response {
         print("Response: n (response)")
         }
         }
         dataTask.resume()
}

而无需使用Alamofire,您可以执行以下操作:

func uploadImage(chosenimage: UIImage) {
    let url = ApiList.base_url + ApiList.uploadFile_Url
    let myUrl = NSURL(string: url)
    let image_data = UIImagePNGRepresentation(chosenimage)
    let tempData = NSMutableData()
    let request = NSMutableURLRequest(url:myUrl! as URL)
    request.httpMethod = "POST"
    let boundary = NSUUID().uuidString
    request.addValue("multipart/form-data; boundary=(boundary)", forHTTPHeaderField:"Content-Type")
    let mimetype = "image/png"
    let fname = "test.png"
    self.body.append("--(boundary)rn".data(using: String.Encoding.utf8)!)
    self.body.append("Content-Disposition:form-data; name="profileUrl"; filename="(fname)"rn".data(using: String.Encoding.utf8)!)
    self.body.append("Content-Type: (mimetype)rnrn".data(using: String.Encoding.utf8)!)
    self.body.append(image_data!)
    self.body.append("rn".data(using: String.Encoding.utf8)!)
    let accessToken = UserDefaults.standard.value(forKey: "accessToken") as? String ?? ""
    let deviceToken = UserDefaults.standard.value(forKey: "deviceToken") as? String ?? singletonclass.instance.getDeviceToken
    let param = [
        "accessToken":accessToken,
        "deviceId":deviceToken,
        "deviceType":"2"
    ]
    for (key,value) in param {
        tempData.append("--(boundary)rn".data(using: String.Encoding.utf8)!)
        tempData.append("Content-Disposition: form-data; name="(key)"rnrn".data(using: String.Encoding.utf8)!)
        tempData.append("(value)rn".data(using: String.Encoding.utf8)!)
    }
    self.body.append(tempData as Data)
    self.body.append("--(boundary)--rn".data(using: String.Encoding.utf8)!)
    request.httpBody = self.body as Data
    let session = URLSession.shared
    let task = session.dataTask(with: request as URLRequest) {
        (
        data, response, error) in
        guard let _:NSData = data! as NSData, let _:URLResponse = response, error == nil else { return }
        do
        {
            let responseDict = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments) as! [String:Any]
            //print("n tyiukmqw",responseDict)
            let code = responseDict.value(forKey: "code") as? String
            let message = responseDict.value(forKey: "Message") as? String
            singletonclass.instance.isrofilePicChagedOrNot = false
            if code == "200"
            {
                print("success code")
                DispatchQueue.main.async(execute: {
                    self.userProfile.image = chosenimage
                    UserDefaults.standard.setValue(UIImagePNGRepresentation(chosenimage), forKey: "UserProfilePicture")
                    singletonclass.instance.userProPic = chosenimage
                })
            }
            else
            {
                DispatchQueue.main.async(execute: {
                    singletonclass.instance.showAlert(message!)
                    self.isActivityIndicatorNeed(false)
                })
            }
        }
        catch
        {
        }
    }
    task.resume()
}

注意:此功能是使用Alamofire上传不同类型的多个文件

// upload file to server
func uploadFiles(files: [Data],completion : @escaping uploadHandler) {
let header : HTTPHeaders = ["Content-Type" : "application/x-www-form-urlencoded"] // if there's Authorization, you may add it in header
let url = URL(string: "Enter the url here")
    Alamofire.upload(multipartFormData: { (multipartFormData) in
        for document in files {
            let fileName = NSUUID().uuidString
            multipartFormData.append(document, withName: "documents", fileName:fileName ,mimeType: "image/jpeg") // You'll have to define the proper mime time for uploading other type of files. You may achieve it by creating a struct and storing the type of each file.
        }
    }, usingThreshold: UInt64.init(), to:url, method: .post, headers: header) { (result) in
        switch result{
        case .success(let upload, _, _):
            upload.responseJSON { response in
                switch response.result {
                case .success(_) : completion(true, nil)
                case .failure(let error) :
                    print("Error in upload: (error.localizedDescription)")
                    completion(false, nil)
                }
            }
        case .failure(let error):
            print("Error in upload: (error.localizedDescription)")
            completion(false,error)
        }
    }
}
typealias uploadHandler = (_ status :Bool,_ error :Error?)->()// Define this anywhere globally 

调用函数时,我要传递一系列文件,我将不同类型的文件转换为数据并将其上传到服务器。

如果要在调用函数之前上传图像数组。

var documents = [Data]()
for image in imageArray {
       if let imgData  = UIImageJPEGRepresentation(image, 1.0) {
        documents.append(document)
         }     
       }

现在您可以调用上传功能并传递文档并收听完成处理程序。

祝你好运。

最新更新