简体   繁体   中英

Download & Upload zip file

I am trying to mimic the following curl:

curl -v -F file=@/Users/myuser/Downloads/shelly-homekit-Shelly25.zip http://10.0.1.7/update

to use the curl command I downloaded the zip file and saved it to my computer.

My app should download the zip file, store it to the device and upload it to the server.

I tried both uploading it as a file and as Data with no success:

            let destination: DownloadRequest.Destination = { _, _ in
                let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
                let fileURL = documentsURL.appendingPathComponent("shelly-homekit-Shelly1PM.zip")

                return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
            }

            AF.download("https://rojer.me/files/shelly/shelly-homekit-Shelly1PM.zip", to: destination).response { response in
                debugPrint(response)

                if response.error == nil, let zipPath = response.fileURL?.path {
                    
                    let url = URL(string: zipPath)!

                    
                    let headers: HTTPHeaders = [
                        .contentType("multipart/form-data")
                    ]
                    
                    if let data = try? Data(contentsOf: url) {
                        AF.upload(data, to: "http://"+dev.ipAddress+"/update",headers: headers).responseDecodable(of: HTTPBinResponse.self) { response in
                            debugPrint(response)
                        }
                    }
                }
            }

I get the following error:

错误图片

Thank you for your help

Like mentioned in the comments you meed to allow arbitrary loads. See Transport security has blocked a cleartext HTTP . For more details

This didn't help:

Like mentioned in the comments you meed to allow arbitrary loads. See Transport security has blocked a cleartext HTTP. For more details

I set the permission as mentioned in the link:

Permission

But getting the following error:

Error

I also made some changes to my code:

                let destination: DownloadRequest.Destination = { _, _ in
                let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
                let fileURL = documentsURL.appendingPathComponent("shelly-homekit-Shelly1PM.zip")

                return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
            }

            AF.download("https://rojer.me/files/shelly/shelly-homekit-Shelly1PM.zip", to: destination).response { response in
                //debugPrint(response)

                if response.error == nil {
                    AF.upload(response.fileURL!, to: "http://"+dev.ipAddress+"/update").responseDecodable(of: HTTPBinResponse.self) { response_up in
                        debugPrint(response_up)
                    }
                }
            }

I used Wireshark to sniff the request sent by the curl command:

POST /update HTTP/1.1
Host: 10.0.1.10
User-Agent: curl/7.64.1
Accept: */*
Content-Length: 988427
Content-Type: multipart/form-data; boundary=------------------------c67b500e63a02f3d
Expect: 100-continue

    

--------------------------c67b500e63a02f3d
Content-Disposition: form-data; name="file"; filename="shelly-homekit-Shelly25.zip"
Content-Type: application/octet-stream

Not sure how to translate it to AF code and add the fileData to the request, it should be a POST request and I believe the following code create the right http body:

                let boundary = "Boundary-\(UUID().uuidString)"

                let headers: HTTPHeaders = [
                    .contentType("multipart/form-data; boundary=\(boundary)")
                ]

                let parameters = [
                  [
                    "key": "file",
                    "value": "shelly-homekit-Shelly25.zip",
                    "type": "application/octet-stream",
                    "src":response.fileURL!.path
                  ]] as [[String : Any]]

                var body = ""
                for param in parameters {
                    let paramName = param["key"]!
                    body += "--\(boundary)\r\n"
                    body += "Content-Disposition:form-data; name=\"\(paramName)\""
                    body += "\r\nContent-Type: \(param["contentType"] as! String)"
                    //let paramSrc = param["src"] as! String
                    let paramValue = param["value"] as! String
                    let paramType = param["type"] as! String
                    //let fileData = try? NSData(contentsOfFile:paramSrc, options:[]) as Data
                    body += "; filename=\"\(paramValue)\"\r\n" + "Content-Type: " + paramType
                }
                let postData = body.data(using: .utf8)

The following code works:

        let data = try? NSData(contentsOf: URL(string:str)!) as Data
    
        AF.upload(multipartFormData: { multipartFormData in
            multipartFormData.append(data!,withName: "file",fileName: file_name ,mimeType: "application/octet-stream")
        }, to: "http://"+dev.ipAddress+"/update")
            .response { response in
                if response.response?.statusCode != 200 {
                    devicesUpdateError.append(dev.name)
                }
            }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM