简体   繁体   中英

Upload files using multipart request - Swift 4

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 ?

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)
        }
    }
}

尝试:

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

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)")

        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM