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

Anticipated input should be in the format of '_item_ in _collection_[ track by _id_]' but instead received

Having trouble with ng-repeat in AngularJS, only showing first element and getting a console error: Expected expression in form of '_item_ in _collection_[ track by _id_]' but got '”pm'. angular.module('DataCabinet') .c ...

Issue with Highcharts: Border of stacking bar chart not visible on the right side

When creating a stacking bar chart, I noticed that the rightmost 'box' does not have a border drawn on the right side. Is there a setting or option in Highcharts that can be used to ensure the white border line is drawn around the 75% box in the ...

The functionality of core-ui-select is not functioning properly following the adjustment of the

I've implemented the jquery plugin "core-ui-select" to enhance the appearance of my form select element. Initially, it was functioning perfectly with this URL: However, after applying htaccess to rewrite the URL, the styling no longer works: I&apos ...

Every time a row is selected, React and material-ui cause all TableRows to be re-rendered anew

Recently, I came across a code snippet that looks like this: <Table selectable onRowSelection={this.onRecordSelected} bodyStyle={tableBodyStyle}> <TableBody deselectOnClickaway={false} showRowHover displayRowCheckbox={false}> ...

Problem with Material-UI Drawer

Is there a way to make this drawer stay fixed on the page like a sticker and remain active without moving when scrolling? I've tried using docked={false}, but it makes the whole page inactive except for the drawer. Any suggestions on how to solve this ...

I was unable to produce the result of the input value entered at the bottom

Is there a way to view the input and output simultaneously in my project? I've seen this done using a button, but I'm looking to achieve the same without a button. How can I do this? <input type="text" id="myText"> <b ...

What is the process of directing to another HTML page within the same Express controller script?

I am looking to switch the initial page (login page) to a second page (admin dashboard) from within the same controller in Express after a specific action has been taken. Here is the relevant code snippet from my controller file nimda.js: function handle ...

Determining the file size of an HTML and JavaScript webpage using JavaScript

Is there a way to determine the amount of bytes downloaded by the browser on an HTML+JS+CSS page with a set size during page load? I am looking for this information in order to display a meaningful progress bar to the user, where the progress advances bas ...

Troubleshooting Issues with Google Analytics Internal Link trackEvent Functionality

Using ga.js, I have encountered an issue with tracking internal links on my website. Despite successfully tracking external links and viewing real-time reports for events, the internal links are not being recorded accurately. While testing pages, the tot ...

Encountering an error message: [$parse:syntax] when trying to implement ng-class

I'm currently working on developing custom form validation, utilizing ng-class to emphasize required fields. Here is the syntax I am using: <div class="form-group" ng-class="{'has-error': dc.{fname}.nedatt({{fname}}.username)}"> ...

Using orchestrate.js for local passport.js authentication

I need assistance finding a tutorial or resources for setting up local passport.js authentication with Orchestrate as the user storage. Most of the resources I have come across are based on MongoDB, but our project requires us to use Orchestrate. Any advic ...

What is the best way to arrange the elements of an array based on a specified value?

Is there a way to develop a function that can organize an array of data based on the value of a specified field? Suppose the field consists of three numbers: 1, 2, 3. The idea is that upon providing a certain value to the function, it will rearrange the ta ...

How can you verify the value of a disabled HTML input element in TestCafe using Typescript?

TestCafe Typescript - how to verify the value of a disabled HTML input element? Despite being disabled for user interaction, I want to ensure that this element still holds the anticipated value. example public async checksomething(text: string) { co ...

A login page designed with jquery does not require resubmission

Encountering an issue where after submitting incorrect login credentials on a webpage, the ajax request fails to go through upon subsequent attempts. After scouring StackExchange for solutions, I have explored threads such as Why won't my jQuery form ...

Is there a way to programmatically toggle a button's enabled state depending on the content of a text input field?

I want to create a functionality where a button will be enabled if the value in a textbox is 'mypassword'. If it's not equal to 'mypassword', then the button should be disabled. I've attempted the code below, but it doesn&apos ...

Sliding out the sidebar menu with Jquery

Hey there! I'm currently working on implementing a swipe feature for the side menu bar. I have already added a click method in my code, but now I also need to incorporate a swipe technique. When the side bar is opened, I want to remove the inside im ...

Error Encountered: Module Not Located

I am encountering an error in my Project where it keeps showing 'Cannot find module' even after numerous attempts to install and uninstall packages simultaneously. The problem persists, and I can't seem to resolve it. { "name&quo ...

Encountering an error: "Unhandled promise rejection SyntaxError: Unexpected character in JSON data at line 1 column 1."

When the submit button is clicked, my registration form data is sent using an event function called postData() in React. The user data is sent at the register route, and I have mentioned line numbers in the comments: const postData = async(event) =>{ ...

Typescript-powered React component for controlling flow in applications

Utilizing a Control flow component in React allows for rendering based on conditions: The component will display its children if the condition evaluates to true, If the condition is false, it will render null or a specified fallback element. Description ...

Getting the user's ID or username into the URL after submitting the login form in Django

In my project folder named startup, I have a login app. The urls.py file for the login app is as follows:- url(r'^$', views.LoginFormView.as_view(), name='index'), This is the URL that leads to the login page. In the views.py file o ...