Swift将具有相关参数的多个文件上载到ASP.NET方法

问题描述 投票:0回答:1

我试图将带有参数的多个文件上传到ASP.NET方法,ASP.NET方法期待一个类的List,我能够发送ASP.NET所期望但我的HttpPostedFile为null :(我的问题我在iOS上做错了什么?这是我用swift编写的iOS函数:

func saveQAPhotos(_ cellHolder: Array<PhotoClass>, completion: @escaping (_ result: String) -> Void)
    {


        //Define Array of Dictionary

        var jsonArrayOfDictionaries = [[AnyHashable: Any]]()

        //For each item in the cellHolder

        for i in 0..<cellHolder.count {

            //Define Dictionary for grading data

            var jsonDict = [AnyHashable: Any]()

            jsonDict["job"] = cellHolder[i].job

            jsonDict["imageBytes"] = cellHolder[i].photo!.base64EncodedString().addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)

            jsonDict["createdBy"] = appDelegate.username

            jsonDict["itemId"] = cellHolder[i].itemId

            jsonArrayOfDictionaries.append(jsonDict)

            jsonDict = [AnyHashable: Any]()

        }

        let jsonData: Data? = try? JSONSerialization.data(withJSONObject: jsonArrayOfDictionaries, options: .prettyPrinted)

        let urlComponents = NSURLComponents(string: webservice + "uploadQAImage");

        urlComponents?.user = appDelegate.username;

        urlComponents?.password = appDelegate.password;

        let url = urlComponents?.url;

        var request = URLRequest(url: url!)

        request.setValue("application/json", forHTTPHeaderField: "Content-Type")

        request.setValue("application/json", forHTTPHeaderField: "Accept")

        request.setValue("multipart/form-data", forHTTPHeaderField: "Content-Type")

        request.httpMethod = "POST"

        request.httpBody = jsonData

        URLSession.shared.dataTask(with: request, completionHandler: {
            (data, response, error) in

            if(error != nil){

                completion((error?.localizedDescription)!)

            }else{

                let responseString = String(data: data!, encoding: .utf8)

                OperationQueue.main.addOperation({

                    completion(responseString!)

                })
            }

        }).resume()
    }

这是我的一些ASP.NET方法:

public string uploadQAImage(List<FileUploadClass> fileUploads) {

    for (int i = 0; i < fileUploads.Count; i++) {
        HttpPostedFile hfc = fileUploads[i].imageBytes;
    }

}

当我向相关文件发送iOS数据时,hfc始终为null。我确实在我的应用程序上安装了Alamofire,我可以使用它,但是我可以使用上传方法发送ASP.NET所期望的吗?

这是我的模特

public class FileUploadClass
    {
        public string job { get; set; }
        public string createdBy { get; set; }
        public HttpPostedFile imageBytes { get; set; }
        public int itemId { get; set; }

    }

这是我的快速课程

class PhotoClass: NSObject {

    var job: String?

    var photo: Data?

    var itemId: Int?

    init(job: String?, photo: Data, itemId: Int?)
    {
        self.job = job

        self.photo = photo

        self.itemId = itemId
    }

}
c# ios asp.net swift alamofire
1个回答
0
投票

根据to the documentation,预期格式为multipart/form-data的MIME HttpPostedFile

文件以MIME multipart / form-data格式上传。默认情况下,大于256 KB的所有请求(包括表单字段和上载文件)都缓冲到磁盘,而不是保存在服务器内存中。

您正在发送某种JSON格式的POST正文并将其称为multipart,但您需要实际发送多部分MIME。描述多部分MIME格式的RFC在这里:https://www.w3.org/Protocols/rfc1341/7_2_Multipart.html

不幸的是,我还没有使用任何可以为您执行此编码的库。这个看起来很容易使用:https://github.com/Fyrts/Multipart - 这是一个例子:

import Multipart

let fileContents = try! Data(contentsOf: URL(string: "/Users/user/Desktop/document.pdf")!)

var message = Multipart(type: .formData)
message.append(Part.FormData(name: "message", value: "See attached file."))
message.append(Part.FormData(name: "file", fileData: fileContents, fileName: "document.pdf", contentType: "application/pdf"))

var request = URLRequest(url: URL(string: "https://example.com")!)
request.httpMethod = "POST"
request.setMultipartBody(message)

URLSession.shared.dataTask(with: request) { data, response, error in
    print(data, response, error)
}.resume()
© www.soinside.com 2019 - 2024. All rights reserved.