我的设备上有这个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&#34; FileUpload =@build.txt&#34; myipaddress /上传
它给了我:FAILED(它来自服务器)
出了什么问题?!
答案 0 :(得分:1)
好的,让我们一步一步。
脚本将数据发布到的URL由此行表示:
xhr.open("POST", 'upload', true);
因此,我们知道您需要点击的端点是yourdomain.com/upload
我们从这一行看到:
xhr.setRequestHeader('X-Filename', file.name);
请求正在发送包含文件名称的标头,因此我们也一定要包含该标头。
我们也看到它在发送之前将文本编码为二进制文件,因此我们只是发送实际文件而不是先尝试阅读文本或其他任何内容。
所以,把它们放在一起,你得到这样的东西:
curl -H "X-Filename: yourFileName" -X POST -d @yourFileName http://yourdomain.com/upload
请注意,如果您在本地执行此操作并且未设置主机文件,则该网址可能会替换为ipaddress/upload
。您可能还需要一个PORT,具体取决于您的配置以及您是否在本地执行此操作。这看起来像是:ipaddress:port/upload