CrazySabbath
CrazySabbath

Reputation: 1334

Angular FormData filename encoding

I'm having problems with angular file upload filename ecoding.

Example: uploading file žžž.txt. Result: žžž.txt

Relevent Html form parts:

<form id="fileupload"
action="/filestore/services/process/upload"
method="POST"
enctype="multipart/form-data"
data-ng-app="MyApp"
data-ng-controller="DemoFileUploadController"
data-file-upload="options"


<input type="file" name="files[]" multiple ng-disabled="disabled" file-change="uploadFile($event, files)">

File controller:

$scope.uploadFile = function($event, files) {
    var file = files[0];
    var data = new FormData();
    console.log(file);
    console.log(data);
    data.append('file-0', file);
    $.ajax({
        url: uploadUrl,
        data: data,
        cache: false,
        contentType: false,
        processData: false,
        type: 'post',
        success: function(data) {
            $scope.reload();
        }
    });
};

File object (printed by console.log(file)):

lastModified 1467975647307
lastModifiedDate Date {Fri Jul 08 2016 14:00:47 GMT+0300 (FLE Standard Time)}
name "žžž.txt"
size 7
type "text/plain"

Post request data body:

Source
-----------------------------2159279631001
Content-Disposition: form-data; name="file-0"; filename="žžž.txt"
Content-Type: text/plain


-----------------------------2159279631001--

As you can see from data/code, FormData is forming data object with incorrect filename, while File object itself is correct...any ideas why is that? How should I solve this?

Edit:

Request headers:

Content-Type multipart/form-data; boundary=---------------------------9275749615024
User-Agent Mozilla/5.0 (Windows NT 10.0; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0
X-Requested-Wit XMLHttpRequest

Response headers:

Content-Length 337
Content-Type application/json;charset=UTF-8
Server Apache-Coyote/1.1

Upvotes: 0

Views: 4910

Answers (1)

Arno_Geismar
Arno_Geismar

Reputation: 2330

You should set the contentType and encoding on your ajax request.

$.ajax({
        url: uploadUrl,
        data: data,
        cache: false,
        contentType: "application/x-www-form-urlencoded;charset=UTF-8",
        processData: false,
        type: 'post',
        success: function(data) {
            $scope.reload();
        }
    });

note that you should change charset To the specific charset you are using and wich contains ž

Also if you are using a backend. Make sure it uses the correct character encoding as well

UTF-8 should do the trick

Upvotes: 0

Related Questions