【问题标题】:Upload files using multipart request - Swift 4使用多部分请求上传文件 - Swift 4
【发布时间】:2018-10-25 04:09:19
【问题描述】:

我必须使用多部分请求在服务器上上传文件。对于网络通话,我使用的是 Alamofire。

到目前为止我所做的如下

请求服务:

多部分请求:-

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

        })

回应:-

{ 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";
}

谁能告诉我我在请求中做错了什么?

【问题讨论】:

  • 你可以使用 alamofire
  • 我提出的要求是用 alamofire。
  • 你是上传单张图片还是多张图片
  • 你试过multipartFormData.append(fileData, withName: "file", fileName: "file", mimeType: "image/png")吗?
  • @GreyHands 请在回答中发布上述行。我会接受它。它有效。

标签: ios iphone swift file-upload alamofire


【解决方案1】:

尝试:

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

【讨论】:

    【解决方案2】:

    我创建了一个函数。希望它对你有用。

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

    【讨论】:

    • 我的和你的差不多。我仍然收到错误请求的错误。
    • 什么是状态码,在邮递员中工作,网络方法对吗?
    • 您是如何发送数据的?参数传递有问题
    • 那个 FileData() 是什么?是数据类型吗?查看我的代码 var 数据:数据? = 无 var 文件名:字符串? = nil if targetListDeviceFilePath != nil { let path = targetListDeviceFilePath?.path data = FileManager.default.contents(atPath: path!) fileName = targetListDeviceFilePath?.lastPathComponent } 我正在从文件管理器中选择文件
    • class func getFileData(path : String) -> Data { if (path.isFileExists()) { let fileURL = path.documentDirectoryPath() let data = try!数据(contentsOf:fileURL)返回数据}返回数据()}
    【解决方案3】:

    试试这个,是一个对我有用的例子。如果要为图像转换编码 64,请添加扩展名。如果只是发布数据和图像,此代码可能会有所帮助。

    //为post请求创建参数

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

    【讨论】:

      猜你喜欢
      • 2015-02-22
      • 2017-02-11
      • 2019-02-06
      • 1970-01-01
      • 1970-01-01
      • 2014-10-10
      • 1970-01-01
      • 1970-01-01
      • 2017-02-25
      相关资源
      最近更新 更多