how to get the uploaded image path in php and ajax

2019-06-14 05:25发布

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

3条回答
疯言疯语
2楼-- · 2019-06-14 05:48

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:

查看更多
Deceive 欺骗
3楼-- · 2019-06-14 05:52
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

查看更多
姐就是有狂的资本
4楼-- · 2019-06-14 05:52

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

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.

查看更多
登录 后发表回答