Upload files using multipart request - Swift 4

情到浓时终转凉″ 提交于 2019-12-12 09:58:45

问题


I have to upload files on server using multipart request. For network calls i am using Alamofire.

What i have done so far is below

Request Service:

Multipart request:-

let headers: HTTPHeaders = [
            "Content-type": "multipart/form-data"
        ]
        let  fileData = Filedata() // getting data from local path

        let URL = try! URLRequest(url: "https://SomeUrl/upload", method: .post, headers: headers)
        Alamofire.upload(multipartFormData: { (multipartFormData) in

             //multipartFormData.append(fileData, withName: "image", fileName: "image", mimeType: "image/png")
               multipartFormData.append(fileData, withName: "file")

        }, with: URL, encodingCompletion: { (result) in

            switch result {
            case .success(let upload, _, _):

                upload.responseJSON { response in
                    print(response)
                }
            case .failure(let encodingError):
                print(encodingError)
            }

        })

Response:-

{ Status Code: 400, Headers {
    Connection =     (
        close
    );
    "Content-Type" =     (
        "application/json;charset=UTF-8"
    );
    Date =     (
        "Tue, 15 May 2018 10:34:15 GMT"
    );
    "Transfer-Encoding" =     (
        Identity
    );
} }
[Data]: 171 bytes
[Result]: SUCCESS: {
    error = "Bad Request";
    message = "Required request part 'file' is not present";
    path = "/files/safebolt.org/upload";
    status = 400;
    timestamp = "2018-05-15T10:34:15.715+0000";
}

Can anyone please tell me what i am doing wrong with request ?


回答1:


Try with:

multipartFormData.append(fileData, withName: "file", fileName: "file", mimeType: "image/png")



回答2:


I have created one function. Hope it works for you.

//Alamofire file upload code
func requestWith(URLString: String,
                 imageData: Data?,
                 fileName: String?,
                 pathExtension: String?,
                 parameters: [String : Any],
                 onView: UIView?,
                 vc: UIViewController,
                 completion:@escaping (Any?) -> Void,
                 failure: @escaping (Error?) -> Void) {

    let headers: HTTPHeaders = [
        "Content-type": "multipart/form-data"
    ]

    let URL = BASE_PATH + URLString
    Alamofire.upload(multipartFormData: { (multipartFormData) in
        for (key, value) in parameters {
            multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key as String)
        }

        if let data = imageData {
            multipartFormData.append(data, withName: "fileUpload", fileName: "\(fileName!).\(pathExtension!)", mimeType: "\(fileName!)/\(pathExtension!)")
        }

    }, usingThreshold: UInt64.init(), to: URL, method: .post, headers: headers) { (result) in

        switch result {
        case .success(let upload, _, _):
            upload.responseJSON { response in
                if let err = response.error {
                    failure(err)
                    return
                }
                completion(response.result.value)
            }
        case .failure(let error):
            print("Error in upload: \(error.localizedDescription)")
            failure(error)
        }
    }
}



回答3:


Try This, is an example it works for me. If you want to convert encode 64 for images add extension. If simply post the data and image this code may help.

//creating parameters for the post request

    let parameters: Parameters=[

        "ad_title":classText1.text!,
        "ad_description":classText2.text!,
        "ad_category":CategoryClass.text!,
        "ad_condition":classText3.text!,
        "ad_username":classText6.text!,
        "ad_usermobile":classText7.text!,
        "ad_city":classText8.text!,
        "ad_price":classText4.text!,
        "negotiable":classText5.text!,
        "image1":adImage1.image!,
        "image2":adImage2.image!,
        "image3":adImage3.image!,
        "image4":adImage4.image!


    ]
    Alamofire.upload(multipartFormData: { (multipartFormData) in
        for (key, value) in parameters {
            multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key as String)
        }


    }, usingThreshold: UInt64.init(), to: URL, method: .post) { (result) in
        switch result{
        case .success(let upload, _, _):
            upload.responseJSON { response in
                print("Succesfully uploaded  = \(response)")
                if let err = response.error{

                    print(err)
                    return
                }

            }
        case .failure(let error):
            print("Error in upload: \(error.localizedDescription)")

        }
    }


来源:https://stackoverflow.com/questions/50348265/upload-files-using-multipart-request-swift-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!