gpt4 book ai didi

javascript - 将 javascript Http Upload 脚本转换为 Curl 命令

转载 作者:行者123 更新时间:2023-11-28 00:41:20 25 4
gpt4 key购买 nike

我有一个设备,其 Web 界面上有此 javascript 函数:

function upload() {
$( "#progress" ).empty();
$( "#uploadresult" ).empty();

// take the file from the input
var file = document.getElementById('files').files[0];
var reader = new FileReader();
reader.readAsBinaryString(file); // alternatively you can use readAsDataURL
reader.onloadend = function(evt)
{
// create XHR instance
xhr = new XMLHttpRequest();

// send the file through POST
xhr.open("POST", 'upload', true);
xhr.setRequestHeader('X-Filename', file.name);

// make sure we have the sendAsBinary method on all browsers
XMLHttpRequest.prototype.mySendAsBinary = function(text){
var data = new ArrayBuffer(text.length);
var ui8a = new Uint8Array(data, 0);
for (var i = 0; i < text.length; i++) ui8a[i] = (text.charCodeAt(i) & 0xff);

if(typeof window.Blob == "function")
{
var blob = new Blob([data]);
}else{
var bb = new (window.MozBlobBuilder || window.WebKitBlobBuilder || window.BlobBuilder)();
bb.append(data);
var blob = bb.getBlob();
}

this.send(blob);
}

// let's track upload progress
var eventSource = xhr.upload || xhr;
eventSource.addEventListener("progress", function(e) {
// get percentage of how much of the current file has been sent
var position = e.position || e.loaded;
var total = e.totalSize || e.total;
var percentage = Math.round((position/total)*100);

// here you should write your own code how you wish to proces this
$( "#progress" ).empty().append('uploaded ' + percentage + '%');
});

// state change observer - we need to know when and if the file was successfully uploaded
xhr.onreadystatechange = function()
{
if(xhr.readyState == 4)
{
if(xhr.status == 200)
{
// process success
$( "#uploadresult" ).empty().append( 'Uploaded Ok');
}else{
// process error
$( "#uploadresult" ).empty().append( 'Uploaded Failed');
}
}
};

// start sending
xhr.mySendAsBinary(evt.target.result);
};
}

在我看来,它正在使用 POST 上传文件,我正在尝试使用 CURL 命令行将文件上传到它,但它一直失败,这是我正在使用的命令: curl -F "FileUpload=@build.txt"myipaddress/upload

它给了我:FAILED(它来自服务器)

怎么了?!

最佳答案

好的,让我们逐步完成这个过程。

脚本将数据发布到的 URL 由这一行表示:

xhr.open("POST", '上传', true);

因此,我们知道您需要访问的端点是 yourdomain.com/upload

从这一行我们看到:

xhr.setRequestHeader('X-Filename', file.name);

该请求正在发送带有文件名的 header ,因此我们也一定会包含该 header 。

我们还看到它在发送之前将文本编码为二进制,因此我们将只发送实际文件,而不是首先尝试读取文本或任何内容。

所以,把它们放在一起,你会得到这样的结果:

curl -H "X-文件名: yourFileName"-X POST -d @yourFileName http://yourdomain.com/upload

请注意,如果您在本地执行此操作且未设置主机文件,则该 URL 可能会替换为 ipaddress/upload。您可能还需要一个端口,具体取决于您的配置以及您是否在本地执行此操作。看起来像:ipaddress:port/upload

关于javascript - 将 javascript Http Upload 脚本转换为 Curl 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27884227/

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