简体   繁体   中英

Upload non-latin name file with jQuery

I have simple form to ajax-upload files to server.

Here is input event listener:

$(document).on('change', '.js-file', function(event){

    sendFile(event);
});

And here is the function that actually uploads the file:

function sendFile (event) {
    var files = event.target.files;


    var action = '/ajax-upload-files/';
    var data = new FormData();

    $.each(files, function(key, value)
    {
        data.append(key, value);
    });

    $.ajax({
        url: action,
        type: 'POST',
        data: data,
        cache: false,
        dataType: 'json',
        processData: false,
        contentType: false,
        success: function(data){

        },
        complete: function(data) {
        }
    });
}

It wors fine with all kinds of files, except those with non-latin characters in the file name, eg Максим.jpg

The data is being sent to server, as I see in Chrome network. But when I try to dump $_FILES on server, it seems to be empty.

var_dump($_FILES) //array(0) {}

I don't really understand what's wrong - contentLength of the request header is much smaller then it should be - it looks like file was not appended to form for some reason.

I finally managed to upload non-latin name file. Have to read it as binary and send as binary.

HTML:

<input class="js-file" name="filename" type="file">

And js

//Handler in input
$(document).on('change', '.js-file', function(event){
            var file_name = $(this).attr('name');


            var reader = new FileReader();
            var f = event.target.files[0],
                nameArr = event.target.files[0]['name'].split('.'),
                extension = nameArr[nameArr.length-1]; //here we can check if extension is allowed

            reader.onload = function(e) {
                var contents = e.target.result;
                contents = contents.split('base64,')[1]; //we need only encoded part

                sendFileAsBinary(file_name, extension, contents);
            };

            reader.readAsDataURL(f);


        });

And sender:

function sendFileAsBinary(file_name, extension, img) {

    $.ajax({
        url: '/ajax-upload-files/',
        type: 'POST',
        data: {
            name: file_name,
            img: img,
            extension: extension
        },
        dataType: 'json',
        success: function(data){


        },
        complete: function(data) {

        }

    })

}

And php code to decode image:

 $name = $this->_getParam('name');
 $extension = $this->_getParam('extension');
 $computedName = $name . '.' . $extension;

 $fileContent = base64_decode($this->_getParam('img'));

 file_put_contents($fileContent, $computedName);

here is the code I'm using(your code):

HTML file

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script src="jquery.min.js"></script>
<script>
$(document).on('change', '#fileToUpload', function(event){
    sendFile(event);
});

function sendFile (event) {
    var files = event.target.files;
    var myAction = 'test.php';
    var myData = new FormData();

    $.each(files, function(key, value){
        myData.append(key, value);
    });

    $.ajax({
        url: myAction,
        type: 'POST',
        data: myData,
        cache: false,
//        dataType: 'json',
        processData: false,
        contentType: false,
        success: function(data){
                    console.log(data);
        },
        complete: function(data) {
        }
    });
}
</script>
</head>

<body>

<form action="test.php" method="post" enctype="multipart/form-data">
    Select image to upload:
    <input type="file" name="fileToUpload" id="fileToUpload">
    <input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>

test.php

<?php
echo var_dump($_FILES);
?>

result in console.log()

<pre class='xdebug-var-dump' dir='ltr'>
<b>array</b> <i>(size=1)</i>
  0 <font color='#888a85'>=&gt;</font> 
    <b>array</b> <i>(size=5)</i>
      'name' <font color='#888a85'>=&gt;</font> <small>string</small> <font color='#cc0000'>'Максим.jpg'</font> <i>(length=16)</i>
      'type' <font color='#888a85'>=&gt;</font> <small>string</small> <font color='#cc0000'>'image/jpeg'</font> <i>(length=10)</i>
      'tmp_name' <font color='#888a85'>=&gt;</font> <small>string</small> <font color='#cc0000'>'C:\wamp\tmp\phpE01A.tmp'</font> <i>(length=23)</i>
      'error' <font color='#888a85'>=&gt;</font> <small>int</small> <font color='#4e9a06'>0</font>
      'size' <font color='#888a85'>=&gt;</font> <small>int</small> <font color='#4e9a06'>951214</font>
</pre>

so, as you can see, my code uploads file and server can see it. do you have different results on your machine?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM