最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - multipart fileupload with formdata - Stack Overflow

programmeradmin1浏览0评论

I'm trying to upload a file with formdata. the file alone works, but I need to upload some userdata. I tried to append formdata, but when i "print_r" the array($_FILES) in the php file called by ajax it doesn't appear there.

If someone has a solution for the issue, or a better way to tackle a fileupload with userdata, please let me know!

Below you can find the code used:

php:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link href="style.css" rel="stylesheet" type="text/css">
<script src="jquery-1.12.0.min.js"></script>


</head>
<body>
<div class="container">
    <h1>AJAX File upload</h1>

    <form method="post" action="" enctype="multipart/form-data" id="myform">
        <input type="text" id="test" value="sample">
        <div >
            <img src="" id="img" width="100" height="100">
        </div>
        <div >
            <input type="file" id="file" name="file" />
            <input type="button" class="button" value="Upload" id="but_upload">
        </div>
    </form>
</div>
</body>
<script type="text/javascript">
$(document).ready(function(){
    $("#but_upload").click(function(){
        //console.log("piemel");
        console.log(document.getElementById('test').value);
        var fd = new FormData();
        var files = $('#file')[0].files[0];
       fd.append('test', document.getElementById('test').value);
        fd.append('file',files);
        console.log(fd);

        $.ajax({
            url:'upload.php',
            type:'post',
            data:fd,
            contentType: false,
            processData: false,
            success:function(response){
                if(response != 0){
                    $("#img").attr("src",response);
                }
            },
            error:function(response){
                alert('error : ' + JSON.stringify(response));
            }
        });
    });
});


</script>
</html>

Ajax file:

<?php

/* Getting file name */

$filename = $_FILES['file']['name'];

/* Location */
$location = "upload/".$filename;

/* Upload file */
if(move_uploaded_file($_FILES['file']['tmp_name'],$location)){
   echo $location;
}else{
    echo 0;
}

I'm trying to upload a file with formdata. the file alone works, but I need to upload some userdata. I tried to append formdata, but when i "print_r" the array($_FILES) in the php file called by ajax it doesn't appear there.

If someone has a solution for the issue, or a better way to tackle a fileupload with userdata, please let me know!

Below you can find the code used:

php:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link href="style.css" rel="stylesheet" type="text/css">
<script src="jquery-1.12.0.min.js"></script>


</head>
<body>
<div class="container">
    <h1>AJAX File upload</h1>

    <form method="post" action="" enctype="multipart/form-data" id="myform">
        <input type="text" id="test" value="sample">
        <div >
            <img src="" id="img" width="100" height="100">
        </div>
        <div >
            <input type="file" id="file" name="file" />
            <input type="button" class="button" value="Upload" id="but_upload">
        </div>
    </form>
</div>
</body>
<script type="text/javascript">
$(document).ready(function(){
    $("#but_upload").click(function(){
        //console.log("piemel");
        console.log(document.getElementById('test').value);
        var fd = new FormData();
        var files = $('#file')[0].files[0];
       fd.append('test', document.getElementById('test').value);
        fd.append('file',files);
        console.log(fd);

        $.ajax({
            url:'upload.php',
            type:'post',
            data:fd,
            contentType: false,
            processData: false,
            success:function(response){
                if(response != 0){
                    $("#img").attr("src",response);
                }
            },
            error:function(response){
                alert('error : ' + JSON.stringify(response));
            }
        });
    });
});


</script>
</html>

Ajax file:

<?php

/* Getting file name */

$filename = $_FILES['file']['name'];

/* Location */
$location = "upload/".$filename;

/* Upload file */
if(move_uploaded_file($_FILES['file']['tmp_name'],$location)){
   echo $location;
}else{
    echo 0;
}
Share Improve this question asked Sep 18, 2017 at 16:45 Achiel VolckaertAchiel Volckaert 1,01412 silver badges29 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 2

I have an example working demo code for this (I was also facing this issue and created this script)

index.php

<script src="https://ajax.googleapis./ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<form id="uploadForm" action="upload.php" method="post">
<label>Upload Image File:</label><br/>
<input name="userImage" type="file" class="inputFile" />
<input type='text' name="my_name" value="harish">
<input type="submit" value="Submit" class="btnSubmit" />
</form>

<script type="text/javascript">

$(document).ready(function (e) {

    $("#uploadForm").on('submit',(function(e) {

    e.preventDefault();

    $.ajax({

            url: "upload.php",
            type: "POST",
            data:  new FormData(this),
            contentType: false,
            cache: false,
            processData:false,

            success: function(data){
                $("#targetLayer").html(data);
            },
            error: function(){}             
        });

    }));

});

</script>

upload.php

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

if(isset($_FILES["userImage"]["type"]))
{
    $validextensions = array("jpeg", "jpg", "png");
    $temporary = explode(".", $_FILES["userImage"]["name"]);
    $file_extension = end($temporary);

    $file_type = $_FILES["userImage"]["type"];

    if ((($file_type == "image/png") || ($file_type == "image/jpg") || ($file_type == "image/jpeg")
    ) /*&& ($_FILES["file"]["size"] < 100000)*/ //Approx. 100kb files can be uploaded.
    && in_array($file_extension, $validextensions))
    {
        if ($_FILES["userImage"]["error"] > 0)
        {
            echo "Return Code: " . $_FILES["userImage"]["error"] . "<br/><br/>";
        }
        else
        {
            if (file_exists("uploads/" . $_FILES["userImage"]["name"] . '-'.time()))
            {
                echo $_FILES["userImage"]["name"] . time() ." <span id='invalid'><b>already exists.</b></span> ";
            }
            else
            {
                $sourcePath = $_FILES['userImage']['tmp_name']; // Storing source path of the file in a variable
                $targetPath = "uploads/".$_FILES['userImage']['name'].'-'.time(); // Target path where file is to be stored

                //check the writable permissions

                /*if (is_writeable('uploads/' . $_FILES['userImage']['name'])) {
                   die("Cannot write to destination file");
                }*/

                if(move_uploaded_file($sourcePath,$targetPath)) {

                    echo "<span id='success'>Image Uploaded Successfully...!!</span><br/>";
                    echo "<br/><b>File Name:</b> " . $_FILES["userImage"]["name"] . "<br>";
                    echo "<b>Type:</b> " . $_FILES["userImage"]["type"] . "<br>";
                    echo "<b>Size:</b> " . ($_FILES["userImage"]["size"] / 1024) . " kB<br>";
                    echo "<b>Temp file:</b> " . $_FILES["userImage"]["tmp_name"] . "<br>";

                } else {

                    echo "<pre>"; print_r($_FILES['file']['error']); echo "</pre>";
                }
            }
        }
    }
    else
    {
    echo "<span id='invalid'>***Invalid file Size or Type***<span>";
    }
}
?>

*Create a folder upload on the same level or change the upload path and make sure to give it writable permissions.

This script is working for both data and files, For post data you need to use $_POST['post_input'].

Give this script a go and hope it will help you.

$_FILES is for files not for data as you are sending data by post use $_POST

Hm. are you trying to upload large files? Because when i was messing around with $_FILES, uploading files bigger than 20mb was unsuccessful until i put the maximum file for upload in my IIS to maximum i could of transfer large files. Only thing i could upload without messing with IIS was normal images.

Your code doesnt seem wrong as it has to put the temp file into the location you provided so What are you exactly trying to upload? The folder "upload" that you are using in your code, does it exist? it wont move any files if the folder doesnt exist either

发布评论

评论列表(0)

  1. 暂无评论