Failing to Upload Picture with multipart/form-data to a Server

这一生的挚爱 提交于 2019-12-08 16:11:30

I debugged your code, simplified and left the debug statements in for clarity. Here is what I came up with:

func postData() {
    var request = URLRequest(url: URL(string: "http://localhost/uploadimages/uploadtry.php")!)
    request.httpMethod = "POST"
    request.timeoutInterval = 30.0

    guard let imageData = UIImagePNGRepresentation(pictureView.image!) else {
        print("oops")
        return
    }

    let CRLF = "\r\n"
    let filename = "user.png"
    let formName = "file"
    let type = "image/png"     // file type

    let boundary = String(format: "----iOSURLSessionBoundary.%08x%08x", arc4random(), arc4random())

    var body = Data()

    // file data //
    body.append(("--\(boundary)" + CRLF).data(using: .utf8)!)
    body.append(("Content-Disposition: form-data; name=\"\(formName)\"; filename=\"\(filename)\"" + CRLF).data(using: .utf8)!)
    body.append(("Content-Type: \(type)" + CRLF + CRLF).data(using: .utf8)!)
    body.append(imageData as Data)
    body.append(CRLF.data(using: .utf8)!)

    // footer //
    body.append(("--\(boundary)--" + CRLF).data(using: .utf8)!)
    request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")

    //TW debug the body data.
    let theString:NSString = NSString(data: body as Data, encoding: String.Encoding.ascii.rawValue)!
    print(theString)

    request.setValue("\(body.count)", forHTTPHeaderField: "Content-Length")

    request.httpBody = body
    let session = URLSession(configuration: .default)
    session.dataTask(with: request) { (data, response, error) in
        if let error = error {
            print(error)
        }
        if let respose = response {
            print(respose)
        }
        // TW
        if let data = data {
            // This gives us same as server log

            // You can print out response object
            print("******* response = \(String(describing: response))")

            print(data.count)
            // you can use data here

            // Print out reponse body
            let responseString = NSString(data: data, encoding: String.Encoding.utf8.rawValue)
            print("****** response data = \(responseString!)")

        }

        }
        .resume()
}

The mentioned uploadtry.php

<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);

$dir = 'media';
$path = $dir . "/" . basename($_FILES['file']['name']);


$data['result'] = 'failure';
if (move_uploaded_file($_FILES['file']['tmp_name'], $path)) {
    chmod($path, 0777);
    $data['result'] = ' success';
}

header('Content-Type: application/json');
echo json_encode($data);


?>

Basically I saw errors like this on the server:

Undefined index: filename in /pathtoserver/uploadimages/uploadtry.php on line 6

So the server could not understand filename in your message. The debug statements help you to see the error also on the client side if you have no server access.

Hope that gets you started.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!