javascript - Ajax File Upload - Script Writes garbage in File -
i have problem ajax-fileupload script. when upload files, files corrupt. when open file notepad++, see there example following lines:
-----------------------------22998260013704
content-disposition: form-data; name="0"; filename="myimage.png"
content-type: image/png
filecontent
-----------------------------22998260013704--
when delete 3 lines bevor filecontent und line after filecontent, file ok. have no clue, why these 4 lines written files. hope can me.
here javascript-code:
var myfiles = []; function ajaxfileupload() { var dataid = document.getelementbyid("dataid").getattribute("data-id"), data = new formdata(), maxsize = 100.0, file = null, myurl = "xxx/save"; $.each(myfiles, function(key, value) { console.log(key+" "+value); file = value; data.append(key, value); }); var filesize = file.size; if ((filesize/(1024*1024)) <= maxsize) { $.ajax({ type: "put", //<-- http://stackoverflow.com/questions/10475313/ajax-file-upload-with-xmlhttprequest url: myurl, processdata: false, contenttype: false, data: data, beforesend: function(xhr) { xhr.setrequestheader("x-file-name", file.name); xhr.setrequestheader("x-file-size", file.size); xhr.setrequestheader("x-myid", dataid); }, success: function (json) { //.... }, }); } else { //... } } and here relevant php-code:
private function copyputfilestotmp($directory = "") { $temp = "xxx"; if (!is_dir($temp)) { mkdir ($temp, 0777, true); } $tmppath = $temp."/"; $filename = $_server['http_x_file_name']; $in = fopen('php://input', 'r'); $ziel = $tmppath.$filename; if (!file_exists($ziel)) { $fileuploadok = true; $out = fopen($ziel, 'w'); $data = fread($in, 1024); while($data) { if ($data != false) { fwrite($out, $data); } else { $fileuploadok = false; } $data = fread($in, 1024); } fclose($in); fclose($out); if ($fileuploadok === false) { //... } else { //... } } else { //... } return $answer; }
i found problem. if sent file directly data , not within formdata works!
so right code is:
var myfiles = []; function ajaxfileupload() { var dataid = document.getelementbyid("dataid").getattribute("data-id"), maxsize = 100.0, file = null, myurl = "xxx/save"; $.each(myfiles, function(key, value) { file = value; }); var filesize = file.size; if ((filesize/(1024*1024)) <= maxsize) { $.ajax({ type: "put", //<-- https://stackoverflow.com/questions/10475313/ajax-file-upload-with-xmlhttprequest url: myurl, processdata: false, contenttype: false, data: file, beforesend: function(xhr) { xhr.setrequestheader("x-file-name", file.name); xhr.setrequestheader("x-file-size", file.size); xhr.setrequestheader("x-myid", dataid); }, success: function (json) { //.... }, }); } else { //... } } found here: ajax file upload xmlhttprequest
Comments
Post a Comment