2

So I am trying to check if a pdf file exists on my server or not.

PDF files are named in korean like abc.com/토보토보.pdf

I have tried :

function UrlExists(url)
{
    var http = new XMLHttpRequest();
    http.open('HEAD', url, false);
    http.send();
    console.log(http.status);
}

But the problem is it always encoded to example.com/%C3%AD%C2%86%C2%A0%C3%AB%C2%B3%C2%B4%C3%AD%C2%86%C2%A0%C3%AB%C2%B3%C2%B4.pdf

UrlExists("example.com/토보토보.pdf")
01:51:29.144 VM428:14 
HEAD
http://example.com/%ED%86%A0%EB%B3%B4%ED%86%A0%EB%B3%B4.pdf     
404     (Not Found)

How do i get the solution to my problem?

2 Answers2

1

I think maybe you want to run the base filename part of your url through encodeURIComponent before sending the http request out.

This should convert your korean text to the escaped text (with the percentage signs) and then it can find it.

source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent

dmgig
  • 4,400
  • 5
  • 36
  • 47
0

try window.encodeURI or window.encodeURIComponent:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent

// encodes characters such as ?,=,/,&,:
console.log(encodeURIComponent('?x=шеллы'));
// expected output: "%3Fx%3D%D1%88%D0%B5%D0%BB%D0%BB%D1%8B"

console.log(encodeURIComponent('?x=test'));
// expected output: "%3Fx%3Dtest"

or try this:

const pdf = {name:"토보토보"};

fetch(url, {
  method: 'POST', 
  body: JSON.stringify(pdf),
  headers: new Headers({
    'Content-Type': 'application/json'
  })
})
.then(function(res){
  return res.json()
})
.then(function(v){
  // read the result
})

or you could do a GET request by putting JSON as a query param:

const pdf = {name:"토보토보"};
const url = "example.com?pdf=${JSON.stringify(pdf)}"
fetch(url).then(...);
Alexander Mills
  • 90,741
  • 139
  • 482
  • 817
  • Hi Alexander, My file name on the server is 토보토보.pdf , If i use encodeURIComponent on the file name it gives encoded characters which do not match the filename on the server and hence return 404 code. – Yuvraj singh May 08 '18 at 20:30
  • yeah idk, try: https://stackoverflow.com/questions/2742852/unicode-characters-in-urls – Alexander Mills May 08 '18 at 20:37
  • one thing your server could do is receive a JSON request, instead of a plain url, and then look up the PDF to see if it exists – Alexander Mills May 08 '18 at 20:38
  • Using JSON to encode the info is probably a good bet here. Your server has to receive and parse the JSON and then look up the pdf by name. – Alexander Mills May 08 '18 at 20:42