how to get the uploaded image path in php and ajax

2019-06-14 05:50发布

问题:

i have a simple form:

<input type="hidden" name="MAX_FILE_SIZE" value="2097152" id="MAX_FILE_SIZE">
<input type="file" name="file_upload" id="file_upload" class="picture_main">
<input type="submit" name="upload_picture" id="upload_picture" value="Submit">

i am trying to to an ajax upload:

submit.on("click", function(){
        var file = $('#file_upload').val();
        uploadImageAjax(file);
        return false;
});

var uploadmageAjax = function(file)
{
    $.ajax({
        type: "POST",
        url: "/test/index/imageupload",
        data: {
            'file': file
        },
        dataType: "json",
        success: function (data) {
            console.log(data);
        }
    });
}

what i get back is, for example, file: "C:\fakepath\weirdan003-10.jpeg"

but im not sure what that fakepath is !?

if i were to do it in php only i would get the image like this:

if (isset($_POST['upload_picture']) ) {
            $data = $formImageUpload->getValues();
            $pictureName = $data['picture'];
....

and then upload it.

So what i want to figure out is if the ajax call POST's to that action the right file so i can then upload it to the disk.

will $('#file_upload').val(); hold the $_FILE??

any ideas?

thanks

回答1:

var file = $('#file_upload').val();

This will return only a path to file on client machine. for securit reason it is returned like c:\fakepath\file_name.ext. If I remember correctly, in some older browsers it was possible to get a real path. But still, it does not helps you to get a file on server.

For ajax style upload you can use some of plugins you got recommended. Or just use jQuery Forms plugin. It will work very similar to $.ajax.

Now, when file is uploaded correctly, you will find all required info about it in $_FILES

In your case it will be something like $_FILES['file_upload'] where 'file_upload' is a name of your file input.

Now you can move it from temporary storage with move_uploaded_file. And do whatever you want with that file

EDIT: And I see you are using Zend. Take a look at this about how to work with FileUpload element on the server side. With Zend you may use FileUpload methods instead of move_uploaded_file



回答2:

jQuery ajax does not support asynchronous file uploads. See jQuery upload file using jQuery's ajax method (without plugins).

If you want to use ajax file upload, it is recommended to implement plugins:

  • http://valums.com/ajax-upload/ (is my favorite)
  • http://www.webdeveloperjuice.com/2010/02/13/7-trusted-ajax-file-upload-plugins-using-jquery/ lists several more


回答3:

For client side, I suggest you to use a plugin.

  • http://blueimp.github.com/jQuery-File-Upload/
  • http://valums.com/ajax-upload/

For server side, you will need to handle it to read from the stream. I think there is a full example (client and server side) on valums git.