From time to time, I may post files of substantial size

When moving to the next step in the form, I have implemented checks to prevent photos over 10mb and disallow .heic files from being uploaded. Most of the time it works as expected, but occasionally files slip through.

If anyone has suggestions for a more effective solution or insight into why this occasional failure occurs allowing large files or .heic files to pass through, I would greatly appreciate it.

var upload_one = document.getElementById("image_one");

            if(upload_one.files.length > 0) {
                    if (upload_one.files.item(0).size >= '10485760') {
                        upload_one.className += " invalid";
                        valid = false;
                        alert("Photo is too large. Photos need to be under 10mb")
                    }

                    fileName = document.querySelector('#image_one').value;
                    extension = fileName.split('.').pop();

                    if (extension == 'heic') {
                        upload_one.className += " invalid";
                        valid = false;
                        alert("Files can only be .png, .jpg or .jpeg")

                    }
                } 

Answer №1

If you're looking to upload large files directly to an S3 bucket on AWS, consider using a presigned URL. This allows you to generate an upload URL that can be used to transfer files to S3 easily.

One approach is to utilize a lambda function to create the presigned URL and then pass it back to the front end for use.

Backend

const AWS = require("aws-sdk");
const S3 = new AWS.S3();
const { v4: uuidv4 } = require("uuid");

const getUrl = async (params) => {
  return await new Promise((resolve, reject) => {
    S3.getSignedUrl("putObject", params, (err, url) => {
      if (err) {
        reject(err);
      } else {
        resolve({
          statusCode: 200,
          url,
        });
      }
    });
  });
};

exports.handler = async (event, context) => {

  const id = uuidv4();
  const { userId } = event?.queryStringParameters;

  const params = {
    Bucket: process.env.INVOICE_BUCKET,
    Key: `${userId}/${id}.csv`,
    ContentType: `text/csv`,
    ACL: "public-read",
  };
  
  try {
    const { url } = await getUrl(params);
    return handleRes({ message: `Successfully generated url`, url, key: `${id}.csv`, publicUrl: `https://yourBucket.s3.eu-west-1.amazonaws.com/${userId}/${id}.csv` }, 200);
  } catch (e) {
    console.error(e);
    return handleRes({ message: "failed" }, 400);
  }
};

Front end

$(function () {
$("#theForm").on("submit", sendFile);
});

function sendFile(e) {
    e.preventDefault();
    var urlPresigned;
    var publicUrl;
    var key;
    $.ajax({
      type: "GET",
      url: `https://yourId.execute-api.eu-west-1.amazonaws.com/Prod/file-upload-to-bucket?userId=${userId}`,
      success: function (resp) {
        urlPresigned = resp.url;
        publicUrl = resp.publicUrl;
        key = resp.key;
        var theFormFile = $("#theFile").get()[0].files[0];

        $.ajax({
          type: "PUT",
          url: urlPresigned,
          contentType: "text/csv", // Put meme type
          processData: false,
          data: theFormFile,
          success: function () {
            // File uploaded successfully
          },
          error: function (err) {
            console.log(err);
          },
        });
      },
    });
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with JQuery: Inability to deactivate an element after receiving an Ajax response

My dynamic dialogue box, generated via Ajax return, presents a challenge involving the dynamically changing drop-down list element $('#functionSelect'). I require this list to trigger disabling of input fields within the dialogue box upon changes ...

Show the React component once the typewriter effect animation is complete

Hello there, I am looking to showcase my social links once the Typewriter effect finishes typing out a sentence in TypeScript. As someone new to React, I'm not quite sure how to make it happen though. Take a look at the code snippet below: ` import ...

I am currently dedicated to enhancing my background transitions and experimenting with creating smooth fade-ins

I'm almost done with my Weather Forecast page for the FCC challenge. However, I'm not satisfied with how the code for swapping the background works. It just doesn't feel right to me. Unfortunately, I can't figure out how to fix it. Addi ...

Ways to designate a parent element in Vue Draggable when the element is lacking a child

I'm currently incorporating vue-draggable into my project from the following GitHub repository: https://github.com/SortableJS/Vue.Draggable Below is my ElementsList component: <div> <draggable v-model="newElement" :move ...

Run a script on an ajax requested page prior to the page being loaded

My website navigation utilizes AJAX for seamless transitions between pages. Specifically, I have two pages: index.html and profile.html. The structure of both pages is as follows: <html> <head> <script src="script1.js" type="text/javascript ...

javascript / php - modify input fields according to selection change

Can anyone help me with an issue I'm facing? I want to update multiple textfields whenever a new option is selected from my dropdown menu. I've written the following code, but it's not working as expected. Can someone figure out what's ...

Trouble encountered while trying to show information on Tooltip using AngularStrap

I've been attempting to show some information in a Tooltip, but all I see is the Title displayed like this: Below is the HTML code where I'm calling it: <button class="btn btn-primary" type="bu ...

In the Rails environment, it is important to verify that the data sent through $.post method in jQuery is correctly

I’m facing an issue with my jQuery script when trying to post data as shown below: $.post({ $('div#location_select').data('cities-path'), { location_string: $('input#city_name').val() }, }); Although this code work ...

Access the child element of a span by targeting a specific attribute value using Protractor

Trying to check if a popover appears using protractor. Below is the snippet of HTML code with the popover in the last child span: <span tariff-popover="views/popovers/c2g/airport.html" class="ng-isolate-scope"> <span ng-transclude=""> ...

Unable to turn off X-Powered-By: Express

After attempting to use app.disable("x-powered-by"); without success, I came across some helpful posts on the topic: how to remove X-Powered-By in ExpressJS Can't get rid of header X-Powered-By:Express I am using "express": "^4.16.4" as backend a ...

Tips for detecting when the MDC Snackbar has been closed using JavaScript

I'm currently working with Material Design's Snackbar in combination with VueJS. My goal is to detect when the snackbar has finished closing. The Snackbar object does have a property called isOpen, which allows me to check if the snackbar is ope ...

Turn off caching for the 'value' event in the Firebase Realtime Database using JS SDK

When setting up a listener for the realtime database : firebaseDb.ref(ref).on('value', (snapshot) => { console.log('snap', snap); const response = snapshot.val(); }); The snapshot is saved for offline use, and upon page refresh, ...

Solving the Challenge of URL Issue in Ajax Call to MVC Controller

I have searched extensively for a solution to my jQuery/MVC problem, but haven't found one that works. Here is the JavaScript code I am using: $.ajax({ type: "POST", url: '@Url.Action("Search","Controller")& ...

The Axios GET call encountered an error with a status code of 404

I am currently working on developing a blog/articles application using vue.js. This app utilizes axios to retrieve data from my db.json file by making a get request. The objective is to display the selected article's content when it is clicked on from ...

TS2345: The argument provided, which is of type 'Event', cannot be assigned to the parameter expected, which is of type 'HtmlInputEvent'

I am facing an issue while trying to upload a file, and I could use some assistance in resolving it. Angular-----Error: src/app/admin/producto/create-producto-dialog.html:38:47 - error TS2345: Argument of type 'Event' is not assignable to parame ...

Identifying a specific field in a dynamically generated React.js component: Best practices

Currently, I am in the process of developing a form with an undetermined number of sensor fields. The front end has been successfully implemented and now my focus is on extracting user information from these dynamically generated component fields. Here is ...

What is the best way to determine if a Google Apps user is not an administrator?

We have developed an app for Google Apps and incorporated the "Integrate with Google" button [https://developers.google.com/apps-marketplace/button]. One issue we're facing is that when a user clicks on this button, they must be an administrator. Howe ...

The email validation function is not functioning correctly when used in conjunction with the form submission

I'm currently working on my final project for my JavaScript class. I've run into a bit of a roadblock and could use some guidance. I am trying to capture input (all code must be done in JS) for an email address and validate it. If the email is va ...

The functionality for tabbed content seems to be malfunctioning on Chrome and Firefox, however it works perfectly

In my index.js file, I have various functions set up like so: // a and b is placed at index.jsp $("#a").click(function (){ //this works on index.jsp and display.jsp(where the servlets forwards it). $("#b").load('servletA.html?action=dis ...

Maintain the visibility of the jQuery dropdown menu even when navigating to a different page within the

I am experiencing an issue with my dropdown menu. Whenever I click on a "dropdown link", it opens another page on my website, but the menu closes in the process. I want to ensure that the menu stays open and highlights the clicked "dropdown link" in bold. ...