0

I'm trying to upload an image file and store it on my server with the path to the location of the file stored on a Mysql data base. I am using an ajax request to send the data but am having serious issues accessing any parts of the file:

PHP

<input type="file" id="upload_file" name='upload_file' style="width: 0px;height: 0px;">

Calls this javascript

function upload_photo(user_id) {

    var file = document.getElementById('upload_file')

    /* Create a FormData instance */
    var formData = new FormData(form);
    formData.append('user_id', user_id)
    formData.append('file', file)
    request = new ajaxRequest()
    request.open("POST", "edit_details.php", true)
    request.setRequestHeader("Content-type", "multipart/form-data")
    request.onreadystatechange = function () {
        if (this.readyState == 4)
            if (this.status == 200)
                if (this.responseText != null)
                    O('page').innerHTML = this.responseText
    }
    request.send(formData)

}

The request payload looks like this:

------WebKitFormBoundaryFA8fI4XH99ES61F6
Content-Disposition: form-data; name="file"

[object HTMLInputElement]
------WebKitFormBoundaryFA8fI4XH99ES61F6
Content-Disposition: form-data; name="user_id"

1001
------WebKitFormBoundaryFA8fI4XH99ES61F6-- 

But when I call a var_dump($_REQUEST) it prints

Any ideas? I've looked at loads but can't work my way through this issue.

I was talking to a professor at my university and he said that "multipart/form-data" can be a pain to work with, and said I may be better using a PUT?

Donald Duck
  • 8,409
  • 22
  • 75
  • 99

1 Answers1

1

There are 2 things to mention here with this issue.

First, you will need to make some extra work on the client side, in javascript, to pass multi-part data - I suspect this is what your teacher might have been talking about. For that, I'd refer you to this SO answer.

Second, on the server side, unlike all the other form data, files are not in the $_GET, $_POST or $_REQUEST array but in their own $_FILES array instead. I encourage you to read-up on this, but basically, PHP will upload in a temporary location, and you should copy the file to it's final location - then save that path into your database.

Hope this helps!

Community
  • 1
  • 1
nibnut
  • 3,072
  • 2
  • 15
  • 17