For example, I have multiple images in my S3 bucket directory,
but the situation is that I don't know how many images because each directory have a different amount of images.
https://s.dir1/img01.jpg ~ img10.jpg
https://s.dir2/img01.jpg ~ img20.jpg
https://s.dir3/img01.jpg ~ img14.jpg
=> dir1 have 10 image urls, dir2 have 20 image urls, dir3 have 14 image urls
(each image's URL have a simple number name, For convenience)
I need to send XMLHttpRequest to check the last name of the images.
for example, I don't want to make an element <img src="https://s.dir1/img14.jpg >
which does not exist in S3 directory
The problem is this code only work for the last one, (In this case, the result imageList = ["https://s.dir1/img02.jpg"]
),
and I have no idea to check the last number of images in dir1
Then How can I check the last URL name in each S3 directory, I want to make available imageList(array) state in React component.
constructor(props) {
super(props);
this.state = {imageList: []}
}
componentDidMount() {
const pushImage = (newImage) => {
this.setState({imageList: [...imageList, newImage]})
}
this.UrlExists(pushImage);
}
UrlExists = (callback) => {
const url = `https://s.dir1/01.jpg`
const url2 = `https://s.dir1/02.jpg`
const http = new XMLHttpRequest();
const http2 = new XMLHttpRequest();
this.httpRequest(http, url, callback);
this.httpRequest(http2, url2, callback);
}
httpRequest = (http, url, callback) => {
http.open('HEAD', url);
http.onreadystatechange = function() {
if (this.readyState === 4) {
console.log('ready state', this.readyState);
if(this.status >= 400) {
console.log('error');
return 'false!!!';
} else {
callback(url)
return 'true!!!'
}
}
}
http.send();
}
render() {
return (
<div>
{this.state.imageList.map( image => (<img src={image} alt="my image" />))}
</div>
)
}
I write my code by referencing this question: HTTP HEAD Request in Javascript/Ajax?
question from:
https://stackoverflow.com/questions/65844403/how-to-check-the-last-available-item-in-my-s3-bucket-by-using-xmlhttprequest-in 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…