【问题标题】:Append data to post body and upload to api将数据附加到帖子正文并上传到 api
【发布时间】:2019-05-10 15:31:13
【问题描述】:

我正在调用一个 api 并传递一些参数,包括从 icloud 获取一些文件,如 pdf、doc、docx 并调用 api。

现在我从 icloud 中挑选一些文件,我需要传递给 api 调用。问题是我的选择文件(pdf 或 doc)没有转换为 nsdata,字节数为 0。所以它没有附加到我的正文参数。帮我找出我做错的地方

我的代码:

func uploadthefileToserver(){

    if let url = URL(string: "https://www.exampleurl/api"){
        var request = URLRequest(url: url)
        let boundary:String = "Boundary-\(UUID().uuidString)"
        // let request = NSMutableURLRequest(url:myUrl! as URL);
        request.httpMethod = "POST"
        request.timeoutInterval = 10
        request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")

        let postJobData:[String:Any] = ["UserId":"107","name":"hardcodevalue"]
        var dataFile: Data = Data()
        print(fullDestPath)   ///Users/sathish/Library/Developer/CoreSimulator/Devices/4464E7A8-0F38-4802-B645-19721D251054/data/Containers/Data/Application/714B1B8E-5872-42B9-B963-B0C51C9403D7/Documents/NewFileiCloud/iOS.DOCX"
        do{
            dataFile = try NSData.init(contentsOf: URL(fileURLWithPath: fullDestPath, isDirectory: true)) as Data
            print(dataFile)
        }catch{
            print(error)
        }
        if(dataFile==nil)  { return; }
        print(dataFile) //0 bytes
        request.httpBody = createBodyWithParameters(parameters: postJobData, filePathKey: "Resume", FileData: dataFile as NSData , boundary: boundary) as Data
        print(postJobData)
        print(dataFile)

        let task = URLSession.shared.dataTask(with: request as URLRequest) {
            data, response, error in


            if error != nil {
                print("error=\(error)")
                return
            }else if let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue){
                print("****** response data = \(responseString)")
                do {
                    let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary
                    print(json)

                    let status = json!["Success"] as! String
                    let errMessage = json!["Message"] as? String
                    DispatchQueue.main.async() {
                        if status == "1"{
                            print(errMessage)

                        }else{
                            print(errMessage)
                        }
                    }

                }catch{
                    print(error)
                }
            }

        }; task.resume()
    }
}

不确定我在哪里做错了。我放了一些打印函数供参考。

主要部分:

dataFile = try NSData.init(contentsOf: URL(fileURLWithPath:
fullDestPath, isDirectory: true)) as Data

request.httpBody = createBodyWithParameters(parameters: postJobData,
filePathKey: "Resume", FileData: dataFile as NSData , boundary:
boundary) as Data

谢谢

更新:

func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {

        print("url = \(urls)")
        filePathUrl = urls
        print(filePathUrl)
        for urll in filePathUrl{
            filepath = filePathUrl[0] as! URL
            print(filepath)
            filePathString = filepath.path
            urlstr = NSURL(fileURLWithPath: filePathString).lastPathComponent!
            print(urlstr)
            // Data object to fetch weather data
            do {
                let weatherData = try NSData(contentsOf: filepath, options: NSData.ReadingOptions())
                print(weatherData)

            } catch {
                print(error)
            }

        }
        let destPath:NSArray = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) as NSArray
        let fileManager = FileManager.default
        print(destPath, "\n")
        documentDir = destPath[0] as? NSString
        let filePath = documentDir?.appendingPathComponent("NewFileiCloud") as! NSString

      //  if fileManager.fileExists(atPath: filePath as String){

            do {
               // try fileManager.createDirectory(atPath: filePath as String, withIntermediateDirectories: false, attributes: nil)
                fullDestPath = filePath.appendingPathComponent(urlstr)
                print(fullDestPath!) ///Users/sathish/Library/Developer/CoreSimulator/Devices/4464E7A8-0F38-4802-B645-19721D251054/data/Containers/Data/Application/E41634D7-681A-4C09-B3EF-5782CECCF4B0/Documents/NewFileiCloud/filke.pdf
                do{
                    try fileManager.copyItem(atPath: filePathString!, toPath: fullDestPath)
                }catch{
                    print("\n")
                    print(error)
                }
            }catch{
                print(error)
            }
       // }

      // ------- This is the path of the application stored filepath -------------- //

        filePathLabel.text = fullDestPath

// ------------------- ---------------------------------//
// Read a file content
        //     fileContent = fileManager.contents(atPath: fullDestPath as String ) as! NSData
        //       print(fileContent)

        uploadthefileToserver()
    }

 func createBodyWithParameters(parameters: [String: Any]?, filePathKey: String?, FileData: NSData, boundary: String) -> NSData {

        let body = NSMutableData();

        if parameters != nil {
            for (key, value) in parameters! {
                body.appendString(string:"--\(boundary)\r\n")
                body.appendString(string: "Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
                body.appendString(string: "\(value)\r\n")
            }
        }

        return body

        let filename = fullDestPath
        let mimetype = "pdf/docx/text"

        body.appendString(string: "--\(boundary)\r\n")
        body.appendString(string: "Content-Disposition: form-data; name=\"\(filePathKey!)\"; filename=\"\(filename)\"\r\n")
        body.appendString(string: "Content-Type: \(mimetype)\r\n\r\n")
        body.append(FileData as Data)
        body.appendString(string: "\r\n")
        body.appendString(string: "--\(boundary)--\r\n")

        return body
    }

【问题讨论】:

  • /Documents/NewFileiCloud/iOS.DOCX ,您是如何将 iOS.DOCX 添加到文档文件夹的?你能显示那个代码吗?
  • 我是通过模拟器添加的
  • 你必须显示代码。您如何尝试将 .docx 从 icloud 存储到文档目录。
  • @McDonal_11 我已经更新了..即使我的数据为零。它根本没有附加到正文参数
  • 你试过这个罗宾吗?有更新吗?

标签: ios iphone swift xcode data-access


【解决方案1】:

你正在尝试做,

  1. 将 PDFURL 转换为数据

  2. 将数据转换为 .PDF

  3. 将该 .PDF 存储在 Doc.Dir 中。

  4. 从 Doc.Dir 检索该 .PDF 并传递到服务器。

对于上述任务,您必须在Doc.Dir 中创建文件夹NewFileiCloud。然后,将pdfUrl 转换为data 并将该数据写入.pdf 文件,然后从doc.dir 获取.pdf 路径并将其转换为Data 并传递给server

我已经为你做了样品。这会让你满意。

override func viewDidAppear(_ animated: Bool) {

    // I have did sample for you by taking .pdf from bundle.
    if let pathPDF = Bundle.main.path(forResource: "sample", ofType: "pdf") {

        let path = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
        let documentDirectoryPath:String = path[0]
        let fileManager = FileManager()
        var destinationURLForFile = URL(fileURLWithPath: documentDirectoryPath.appending("/NewFileiCloud"))
        do {
            //You have to create directory with above name.
            try fileManager.createDirectory(at: destinationURLForFile, withIntermediateDirectories: true, attributes: nil)
            destinationURLForFile.appendPathComponent("reader.pdf")

            //YOUR PDF URL [pathPDF [my bundle path, you have to give your URL]] to DATA
            let pdfData = try Data(contentsOf: URL(fileURLWithPath: pathPDF))  

            // WRITE ITS CONTENT to Doc.Dir.
            try pdfData.write(to: destinationURLForFile, options:.atomic)

            //ASSIGN PATH TO GLOBAL URL VARIABLE
            fullPAth = destinationURLForFile


            print("conclude     ", destinationURLForFile)

            uploadToServer()

        }
        catch(let error){
            print(error)
        }

    }
}


func uploadToServer() {

    .....

    do {

        // Here you can get PDF contents as Data.
        // With this Data, you can pass to Server Side.
        let pdfPOSTData = try Data(contentsOf: fullPAth!)
    }
    catch let e{
        print("Catch_Not_worlk    ",  e)
    }

    ......
}

【讨论】:

猜你喜欢
  • 2011-11-27
  • 2015-08-09
  • 1970-01-01
  • 1970-01-01
  • 2018-05-09
  • 1970-01-01
  • 2015-05-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多