使用XMLHttpRequest读取文件名包含%的文件

时间:2017-05-17 21:29:53

标签: javascript http xmlhttprequest

我正在使用XMLHttpRequest来读取名为“filename%3Fformat = json”的文件。我收到一个错误,说区域.js:1382 GET http://localhost:3000/file%3Fformat=json 404(未找到)。

如果我将请求更改为“filename3Fformat = json”并将文件名更改为相同(基本上从文件名和请求中删除%,它可以正常工作......但我需要能够包含%在文件名中。

我在绝望中添加了setRequestHeader,但这似乎没有任何区别。

var requestAllStations = new XMLHttpRequest();

requestAllStations.onload = function ( ) {
    if (requestAllStations.readyState == requestAllStations.DONE && requestAllStations.status == 200) {
        // get json file content
        var allFITStations = JSON.parse(requestAllStations.responseText);

        console.log(allFITStations);
    }
};

requestAllStations.open("get", "./file%3Fformat=json", true );
requestAllStations.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
requestAllStations.send();

2 个答案:

答案 0 :(得分:1)

使用Javascript的escape()函数对特殊字符进行编码。

[??? home]$ pip install matlab_kernel
Requirement already satisfied: matlab_kernel in ./ec2-user/anaconda2/lib/python2.7/site-packages
Requirement already satisfied: ipython>=4.0.0 in ./ec2-user/anaconda2/lib/python2.7/site-packages (from matlab_kernel)
Requirement already satisfied: metakernel>=0.18.0 in ./ec2-user/anaconda2/lib/python2.7/site-packages (from matlab_kernel)
Requirement already satisfied: jupyter-client>=4.4.0 in ./ec2-user/anaconda2/lib/python2.7/site-packages (from matlab_kernel)
Requirement already satisfied: backports.tempfile in ./ec2-user/anaconda2/lib/python2.7/site-packages (from matlab_kernel)
Requirement already satisfied: pexpect>=4.2 in ./ec2-user/anaconda2/lib/python2.7/site-packages (from metakernel>=0.18.0->matlab_kernel)
Requirement already satisfied: ipykernel in ./ec2-user/anaconda2/lib/python2.7/site-packages (from metakernel>=0.18.0->matlab_kernel)
Requirement already satisfied: backports.weakref in ./ec2-user/anaconda2/lib/python2.7/site-packages (from backports.tempfile->matlab_kernel)

字符串转义字符串将如下所示:

requestAllStations.open("get", escape("./file%3Fformat=json"), true );

答案 1 :(得分:0)

所以,我最终在请求的文件名中添加了.replace(/%/ g,"%25")。我猜测发生的事情是我的服务器试图将%3F解码为?在文件名中,我进一步编码文件名以包含"%" (%25)。

filename = file?format=json    
encodeURIComponent(filename).replace(/%3D/g, "=").replace(/%/g, "%25"))