首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >使用URLSession.shared.uploadTask上传图片和参数到接口

使用URLSession.shared.uploadTask上传图片和参数到接口
EN

Stack Overflow用户
提问于 2019-04-26 08:34:54
回答 1查看 771关注 0票数 0

我正在尝试解决如何使用swift将一组参数和一个图像文件上传到我的API。

我的代码大致是这样的:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
//parameters
    let actualParameters = ["email": myEmail, "token": myToken, "certnbr": certnbr, "title": title, "newCert": newCert, "expires": expires, "expiryDate": expiryDate, "issueDate": issueDate] as! [String : Any]

    let parameters = NewCertModel(email: "email")

    //create the url with URL
    let url = URL(string: "http://127.0.0.1:8000/api/newCertification/")!

    //now create the URLRequest object using the url object
    var request = URLRequest(url: url)

    request.httpMethod = "POST"
    let boundary = "Boundary-\(UUID().uuidString)"
    request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")

    request.httpBody = createBody(parameters: params,
                            boundary: boundary,
                            data: UIImageJPEGRepresentation(chosenImage, 0.7)!,
                            mimeType: "image/jpg",
                            filename: "hello.jpg")

    guard let uploadData = try? JSONEncoder().encode(parameters) else {
        print("Error Upload Data")
        return
    }


    //new session
    URLSession.shared.uploadTask(with: request as URLRequest, from: jsonData as! Data) { (responseData, response, error) in
                                    // Check on some response headers (if it's HTTP)
                                    if let httpResponse = response as? HTTPURLResponse {
                                        switch httpResponse.statusCode {
                                        case 200..<300:
                                            print("Success")
                                        case 400..<500:
                                            print("Request error")
                                        case 500..<600:
                                            print("Server error")
                                        case let otherCode:
                                            print("Other code: \(otherCode)")
                                        }
                                    }

                                    // Do something with the response data
                                    if let
                                        responseData = responseData,
                                        let responseString = String(data: responseData, encoding: String.Encoding.utf8) {
                                        print("Server Response:")
                                        print(responseString)
                                    }

                                    // Do something with the error
                                    if let error = error {
                                        print(error.localizedDescription)
                                    }
    }

    .resume()
    }
}

代码并不完美,因为我尝试了相当多的解决方案,它们现在有点混乱。我可以很容易地将数据传递给我的api,但文件上传/多部分让我感到困惑。我发现这方面的资源很难找到,而且非常有限,特别是来自一个全职Android开发职位的资源。

我可以切换到Alamofire,但我的整个项目还没有使用它。我想等一下再换。我轻松地花了5个小时尝试组合,以显示最轻微的通过数据,但仍一无所获。

下面是我的python代码的开始:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
if request.method == 'POST':

email = request.POST.get('email')
token = request.POST.get('token')
certnbr = request.POST.get('certnbr')
title = request.POST.get('title')
newCert = request.POST.get('newCert')
expires = request.POST.get('expires')
expirydate = request.POST.get('expiryDate')
issuedate = request.POST.get('issueDate')
picfile = request.FILES.get('image')

data = {}

#get the user
u = Usr.objects.get(email__iexact=email)

一些我不太了解的来源:

fluffy.es -“这段代码在我看来太马虎了?”

medium article -“我在这里找不到传递参数的提示”

stackoverflow

more stackoverflow

further stackoverlow

令我惊讶的是,所有这些来源之间的不一致,只有少数人甚至使用uploadTask,加上我读到了十几个其他似乎不同的来源。Alamofire到底是不是最佳选择?为什么苹果不直接采用它呢?整个过程都出乎意料的困难,提前感谢大家的帮助。

编辑:我切换到了Alamofire,立即变得更容易。

EN

回答 1

Stack Overflow用户

发布于 2019-04-26 09:09:29

虽然对我的问题不是最好的回答,但Alamofire代码更简洁。所以为了给未来的我省去一些压力。只要用Alamofire就行了。

Alamofire Github

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
let ImageData = imageobj.pngData()
    let urlReq = URL(string: "http://127.0.0.1:8000/api/newCertification/")!
    print("params")
    let params : Parameters = ["email": myEmail, "token": myToken, "certnbr": certnbr, "title": title, "newCert": newCert, "expires": expires, "expiryDate": expiryDate as Any, "issueDate": issueDate as Any]
    print("time to upload")
    Alamofire.upload(multipartFormData: { multipartFormData in
        multipartFormData.append(ImageData!, withName: "avatar",fileName: "file.jpg", mimeType: "image/jpg")
        for (key, value) in params {// this will loop the 'parameters' value, you can comment this if not needed
            multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
        }
    },
                     to:urlReq)
    { (result) in
        switch result {
        case .success(let upload, _, _):

            upload.uploadProgress(closure: { (progress) in
                print("Upload Progress: \(progress.fractionCompleted)")
            })

            upload.responseJSON { response in
                //completion("success")
            }

        case .failure(let encodingError):
            print(encodingError)
            //completion("failed")


    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55863760

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
查看详情【社区公告】 技术创作特训营有奖征文