3

I want users to paste in my input a link of a gif or an image.

For example, user pastes this link : https://media.giphy.com/media/yYSSBtDgbbRzq/giphy.gif

I want my application to recognize if this gif is over 5MB, without downloading it. Is that possible?

I am using Reactjs for front-end and nodejs+express for the backend

3 Answers3

3

You could get the content length by only asking for the headers. This is a fetch based approach of this answer here:

Ajax - Get size of file before downloading

const getFileSize = async (url) => {
   const response = await fetch(url, {method: 'HEAD'})

   const size = response.headers.get('content-length')

   return size
}
Einar Ólafsson
  • 3,036
  • 1
  • 19
  • 24
2

The HTTP protocol offers the HEAD method. According to Wikipedia's HTTP-article it is just like the GET method except that it returns only the HTTP-header and not the data.

That may be exactly what you need: issue an AJAX-HEAD-request instead of an AJAX-GET-request and parse the expected size of the image from the result.

I don't know how to formulate this in JS, but the Linux command line proves that the principle works. If I type:

curl --head https://media.giphy.com/media/yYSSBtDgbbRzq/giphy.gif

I get a response from the server containing the line

content-length: 2156106

which is the information you want.

Mark Roberts
  • 138
  • 7
1

You may use <input type="file" class="js-file-upload" /> which will give ability the user to either upload downloaded file or copy/paste there the link of .gif file.

After that from JS side you will need to check size of that file (it will be auto uploaded in temp file in user PC if they paste a direct link).

Here is a simple example

const file = document.querySelector('.js-file-upload').files[0];
const fileSize = (file.size/1024/1024).toFixed(2);
const allowedSize = 5;

if (fileSize > allowedSize) {
     //print error
}
Gesha
  • 703
  • 4
  • 7