阅读远程文件的一部分 [英] Read part of remote file

查看:139
本文介绍了阅读远程文件的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们希望使用Ajax读取其中的一部分远程文件。
如果没有像PHP这样的服务器端技术,我们怎样才能使用JS?

There is a remote file that we want to read part of it, using Ajax. How can we do it just using JS, without server side techs like PHP?

我想我需要使用HTTP Range标头,但是如何设置它用Ajax?是否可以在Ajax中设置HTTP头?

I think I need to use HTTP Range header, but how to set it with Ajax? Is it possible to set HTTP headers in Ajax at all?

推荐答案

您可以通过 setRequestHeader ,例如如果 xhr XMLHttpRequest 实例:

xhr.setRequestHeader('HeaderName', 'HeaderValue');

我刚刚测试了它,这给了我要求的文件的前56个字符:

I just tested it, and this gave me the first 56 characters of the file I requested:

var xhr = new XMLHttpRequest();
xhr.open("get", "thefile");
xhr.setRequestHeader("Range", "bytes=0-100");
xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
        $("<p>").text("status = " + xhr.status + ", length = " + xhr.responseText.length + ", text = " + xhr.responseText).appendTo(document.body);
    }
};
xhr.send();

请注意,状态返回206(部分内容),而不是200.

Note that the status comes back as 206 (Partial Content), not 200.

为什么是56个字符?在我的测试中可能是字节与字符的对比。

Why 56 characters? Probably a bytes vs. characters thing in my test.

这篇关于阅读远程文件的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆