I want to upload a .zip file to user documents in vk.com, the documentation says that for this you need to go through 3 steps:
- Get the server address that I did
At this stage, you need to upload the file, get a JSON object with the file field, which is used in stage 3, but at this stage I always receive
{"error":"unknown error"}Save file
Tell me, please, what am I doing wrong, uploadUrl is the path to the server vk.com, obtained in the first stage.
func uploadFileToServer(_ uploadUrl: String, withFileUrl name: URL, onCompletion:@escaping (_ receivedFile: String?) -> Void) { let url = URL(string:uploadUrl) guard let urlExist = url else { return } var urlRequest = URLRequest.init(url: urlExist, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 30) var dataZip: Data? do { dataZip = try Data.init(contentsOf: name) } catch let error as NSError { print(error.localizedDescription) } var _params: [String : Data] = Dictionary() _params["file"] = dataZip var body = Data() let boundary = "---------------------------0983745982375409872438752038475287" let contentType = "multipart/form-data; boundary=\(boundary)" urlRequest.addValue(contentType, forHTTPHeaderField:"Content-Type") if let zipData = dataZip { body.append("--\(boundary)\r\n".data(using: .utf8)!) body.append("Content-Disposition: attachment; name="Document"; filename=".zip\r\n".data(using: .utf8)!) body.append("Content-Type: application/octet-stream\r\n\r\n".data(using: .utf8)!) body.append(zipData) body.append("\r\n".data(using: .utf8)!) } body.append("--\(boundary)--\r\n".data(using: .utf8)!) urlRequest.httpBody = body urlRequest.httpMethod = "POST" let task = URLSession(configuration: .default).dataTask(with: urlRequest) { [weak self](data, response, error) -> Void in print(response) if let data = data { do { if let returnData = String(data: data, encoding: .utf8) { print(returnData) onCompletion(returnData) } } catch let error as NSError { print(error.localizedDescription) } } else if let error = error { print(error.localizedDescription) } } task.resume() } The post request looks like this:
▿ url : Optional<URL> ▿ some : https://pu.vk.com/c816630/upload.php?act=add_doc&mid=100453791&aid=0&gid=0&type=0&hash=73a86d9f7e3c4f301cd6e270973b9402&rhash=feb4d83139ca61b46b2a0fefba55e1ce&api=1 - cachePolicy : 1 - timeoutInterval : 30.0 - mainDocumentURL : nil - networkServiceType : __ObjC.NSURLRequest.NetworkServiceType - allowsCellularAccess : true ▿ httpMethod : Optional<String> - some : "POST" ▿ allHTTPHeaderFields : Optional<Dictionary<String, String>> ▿ some : 1 element ▿ 0 : 2 elements - .0 : "Content-Type" - .1 : "multipart/form-data; boundary=---------------------------0983745982375409872438752038475287" ▿ httpBody : Optional<Data> ▿ some : 207058 bytes - count : 207058 ▿ pointer : 0x0000000121b29000 - pointerValue : 4860317696 - httpBodyStream : nil - httpShouldHandleCookies : true - httpShouldUsePipelining : false