doufu1504 2019-06-05 12:54
浏览 73

使用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.

  • 写回答

0条回答

    报告相同问题?

    悬赏问题

    • ¥100 Jenkins自动化部署—悬赏100元
    • ¥15 关于#python#的问题:求帮写python代码
    • ¥20 MATLAB画图图形出现上下震荡的线条
    • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
    • ¥15 perl MISA分析p3_in脚本出错
    • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
    • ¥15 ubuntu虚拟机打包apk错误
    • ¥199 rust编程架构设计的方案 有偿
    • ¥15 回答4f系统的像差计算
    • ¥15 java如何提取出pdf里的文字?