How to upload file using ajax

2019-09-14 15:47发布

I was trying to send a single file to the server without having to change the webpage. I decided to use this plugin: http://cmlenz.github.com/jquery-iframe-transport/ I am very confused on how to proceed for an upload without changing the webpage... the uploadimg.php returns:

<br />
<b>Notice</b>:  Undefined index: photo in <b>C:\website\uploadimg.php</b> on line <b>2</b><br />
<br />
<b>Notice</b>:  Undefined index: photo in <b>C:\website\uploadimg.php</b> on line <b>3</b><br />
<img src="userimg/" />

My files:

postAd.php

<html>
<head>
<script src="jquery.js"></script>
<script src="jquery-iframe-transport.js"></script>
<script>
$(document).ready(function(){
    $('#photo1').on('change', function(){
        $.ajax({
            url: "uploadimg.php",
            files: $("#photo1:file"),
            iframe: true,
            processData: false
        }).done(function(data){
            console.log(data);
        });
    });
});
</script>
</head>
<body>
<input type='file' name='photo' id='photo1' /></br>
</body>
</html>

uploadimg.php

<?php 
$file_tmp = $_FILES['photo']['tmp_name'][0];
$file = $_FILES['photo']['name'][0];
move_uploaded_file($file_tmp, "userimg/$file");
echo '<img src="userimg/' .$file .'" />';
?>

标签: ajax file upload
3条回答
小情绪 Triste *
2楼-- · 2019-09-14 16:07

after a lot of searching I found this simple easy file uploading using ajax. you can find it at upload in php without refreshing

查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-09-14 16:08

You are not submitting a form, so the 'photo' field is not going to be sent with the AJAX call. If you have a debugger available, check the $_FILES array to see what got populated. From this, it appears that you might be looking for a 'userfile' index, but I'm not sure.

查看更多
在下西门庆
4楼-- · 2019-09-14 16:10
function upload(event) {

var formData = new FormData($('#uploadForm')[0]);

$.ajax( {             
    url     : "upload.do",
    type        : "POST",
    data    : formData,
    cache   : false,
    contentType     : false,
    processData : false,

});

@RequestMapping(value = "/uploadCsr", method = RequestMethod.POST)
    @ResponseBody
    public String uploadCsr(@RequestParam("fileUpload") MultipartFile file, HttpServletResponse response) {
// read the file using inputstream

}
查看更多
登录 后发表回答