使用Swift将文件上传到带有Slim的服务器(PHP)

When I'm uploading a file to our server running slim (3.x) the server always responds "invalid request, the content-type for POST-requests must be x-www-form-urlencoded" even though it must be sent using "content-type: multipart/form-data" because it contains files.

I've tried the exact same code with a PHP snippet without slim which works absolutely fine. On the slim server it doesn't even start executing because of the error.

    { (...)
        request = NSMutableURLRequest(url: url);
        request.httpMethod = "POST";


        let boundary = generateBoundaryString()

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


        request.httpBody = createBodyWithParameters(params, files: files, boundary: boundary) as Data (...)
     (...)
    }
    func createBodyWithParameters(_ parameters: [String: String]?, files: [uploadFile], boundary: String) -> NSData {
        let body = NSMutableData();

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

")
                body.appendString("\(value)
")
            }
        }


        for file in files {
            let filename = file.name
            let filePathKey = file.fileKey
            let mimetype = file.mimetype

            let data = file.file
            body.appendString("--\(boundary)
")
            body.appendString("Content-Disposition: form-data; name=\"\(filePathKey)\"; filename=\"\(filename)\"
")
            body.appendString("Content-Type: \(mimetype)

")
            body.append(data)
            body.appendString("
")


            body.appendString("--\(boundary)--
")
        }
        return body
    }

When running the Server responds invalid request, the content-type for POST-requests must be x-www-form-urlencoded and doesn't execute the code of the route.

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问