gpt4 book ai didi

javascript - Ajax 文件上传 - 脚本在文件中写入垃圾

转载 作者:行者123 更新时间:2023-11-28 07:15:46 25 4
gpt4 key购买 nike

我的 Ajax-Fileupload 脚本有问题。当我上传文件时,文件已损坏。当我用 Notepad++ 打开文件时,我看到有以下几行:

-----------------------------22998260013704

Content-Disposition: form-data; name="0"; filename="myimage.png"

Content-Type: image/png

filecontent

-----------------------------22998260013704--

当我删除文件内容之前的 3 行和文件内容之后的行时,文件正常。我不知道为什么这 4 行被写入文件。我希望有人能帮助我。

这是我的 Javascript 代码:

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 {
//...
}
}

这里是我的相关 PHP 代码:

 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;
}

最佳答案

我发现了问题。如果我直接将文件作为数据发送而不是在 FormData 中发送,它就可以工作!

所以正确的代码是:

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 {
//...
}
}

在这里找到:AJAX File Upload with XMLHttpRequest

关于javascript - Ajax 文件上传 - 脚本在文件中写入垃圾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30845903/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com