Как отправить запрос multipart / form-data в Swift на этот фрагмент API - PullRequest
1 голос
/ 21 июня 2019

Я пытаюсь загрузить изображение на сервер API в iOS и получаю сообщение об ошибке на сервере.

Ниже мой код загрузки (в Swift), а затем код API (в JavaScript).

func upLoadData(strUrl: String, productionImageData:Data?, parameters: [String : Any]?,completion:@escaping (NSDictionary?,Int)->()){

    let url = strUrl

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

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


        if let productionData = productionImageData{
            print(productionData.count)
            multipartFormData.append(productionData, withName: "file", fileName: "imgData.jpg", mimeType: "image/jpg")
        }

    }, usingThreshold: UInt64.init(), to: url, method: .post, headers: headers) { (result) in
        switch result{
        case .success(let upload,_,_ ):
            upload.responseJSON { response in
                if let data = response.result.value as? NSDictionary {
                    print(data)
                    completion(data,(response.response?.statusCode)!)
                }
                else{
                    ///USUALLY COMES IN THIS CLAUSE
                    print((response.response?.statusCode)!)
                    completion(nil, (response.response?.statusCode)!)
                }
            }

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

// Это API

JavaScript
function CoverImageUpload(req, res, next){
        var id = sanitizer.sanitize(req.body.id);
        var file_path = sanitizer.sanitize(req.files.file.path);
        console.log(req)
        fs.readFile(file_path, (err,data) => {
            if (err) throw err;
            photo.coverImageUpload(id, data)
            .then(function(response){
                console.log(response.result)
                res.send(response)
            })
            .catch(err => res.send(err))

        })
        return next();
    }

Фактический результат будет в основном отвечать json, который включает URL-адрес, где хранится изображение.Однако в настоящее время я получаю HTML-ответ с ошибкой сервера и чувствую, что у меня неправильные параметры / я не настроил правильный вызов JavaScript API.

...