英文:
React checking of a URL exists
问题
可以,你可以在加载组件时检查URL是否有效。如果URL指向一个PDF文件,你可以有条件地显示一个“可下载”按钮,否则不显示任何内容。
英文:
I am building an app at work that with a table the brings up a details page which displays part information, as well as a download link ( ...url/variouspart#.pdf) to a PDF with additional information. The problem lies in that not every part has additional information since information gets added and removed form the directory constantly, so currently if the used hits "download" on a part with no additional info, they get an error.
So my question is, can someone show me a way to check if the URL is valid when I load the component? Then if the URL leads to a PDF, I can conditionally display a "download available" button or display nothing.
答案1
得分: 1
给定的代码根据提供的URL返回信息,具体取决于该位置是否有PDF文件 - 如果有PDF文件,则显示信息。如果给定的URL位置不是PDF文件,而是HTML等其他内容,它将返回不同的消息。如果给定的URL下没有任何内容,它将返回带有HTTP状态的错误。
function checkIfPdfExists(url) {
const xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.responseType = 'blob';
xhr.onload = () => {
if (xhr.status === 200) {
const blob = xhr.response;
// 检查blob是否包含有效的PDF文件
if (blob.type === 'application/pdf') {
// Blob对象包含PDF文件
console.log('成功检索到PDF文件。');
// 在这里可以对PDF文件执行操作
} else {
console.error('检索到的文件不是PDF文件。');
// 处理错误情况
}
} else {
console.error(`请求失败,状态码为 ${xhr.status}。`);
// 处理错误情况
}
};
xhr.send();
}
checkIfPdfExists('https://www.africau.edu/images/default/sample.pdf'); // 成功检索到PDF文件。
请记住正确设置CORS头,否则由于浏览器安全性问题,代码将无法正常工作。
英文:
The given code returns, depending on the given URL, whether there is a PDF file under this location - if there is, it displays information. If the given URL location is not a PDF file, but e.g. HTML, it returns a different message. If nothing exists under the given URL, it returns an error with HTTP status.
function checkIfPdfExists(url) {
const xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.responseType = 'blob';
xhr.onload = () => {
if (xhr.status === 200) {
const blob = xhr.response;
// check if the blob contains a valid PDF file
if (blob.type === 'application/pdf') {
// the Blob object contains a PDF file
console.log('PDF file retrieved successfully.');
// you can do something with the PDF file here
} else {
console.error('The retrieved file is not a PDF file.');
// handle the error case here
}
} else {
console.error(`Request failed with status ${xhr.status}.`);
// handle the error case here
}
};
xhr.send();
}
checkIfPdfExists('https://www.africau.edu/images/default/sample.pdf'); // PDF file retrieved successfully.
Remember to set the CORS headers correctly, otherwise the code will not work due to browser security.
答案2
得分: 1
只有一种真正功能的方式来显示一个像PDF这样的对象是否有效和当前可访问,不需要任何脚本,因为这是一个纯实时的是/否情况。
<html><head></head><body>
这里有3个PDF对象<br><br>
<object data="https://www.africau.edu/images/default/sample.pdf">该引用无法访问或您现在没有插件</object><br>
<object data="file:///C:/local/MyPrivateGasBill.pdf">该引用无法访问或您现在没有插件</object><br>
<object data="https://www.example.com/any.pdf">该引用无法访问或您现在没有插件</object><br>
<hr> 显然有些会显示,而其他些则不会显示
</body></html>
英文:
There is only one really functional means to show an object such as PDF is valid and currently accessible, and there is no need for any scripting as its a pure real time go/no go situation.
<html><head></head><body>
Here are 3 PDF objects<br><br>
<object data="https://www.africau.edu/images/default/sample.pdf">That reference is inaccessible or you dont have a plug-in right now</object><br>
<object data="file:///C:/local/MyPrivateGasBill.pdf">That reference is inaccessible or you dont have a plug-in right now</object><br>
<object data="https://www.example.com/any.pdf">That reference is inaccessible or you dont have a plug-in right now</object><br>
<hr> clearly some will show and others will not
</body></html>
答案3
得分: -1
你想要做的是检查远程资源是否存在。这是使用 HEAD
HTTP 动词的常见用例。与 GET
不同,HEAD
不会返回响应正文(即不会下载实际的 PDF 文件),因此速度更快且成本更低。好的一点是,如果资源不存在,HEAD
仍然会返回 404 状态码。
https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods
由于你正在使用 ReactJS,这里是一个用于验证远程资源存在性的示例 fetch
调用:
const pdfExists = async (url) => {
try {
const response = await fetch(url, { method: 'HEAD' });
return response.status === 200;
} catch (err) {
return false;
}
}
警告:上述代码未经测试,可能需要修改。
英文:
What you want to do is check if the remote resource exists. This is a common use case for the HEAD
HTTP verb. Unlike GET
, HEAD
does not return the response body (i.e. does not download the actual PDF) and as a result, is a lot faster and less costly. The good thing is that HEAD
would still return a 404 status code if the resource does not exist.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods
Since you're using ReactJS, here's a sample fetch
call that you can make to verify the existence of a remote resource:
const pdfExists = async (url) => {
try {
const response = await fetch(url, { method: 'HEAD' });
return response.status === 200;
} catch (err) {
return false;
}
}
WARNING: The above code is not tested and may need modifications.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论