Sharing image using the MEAN stack

While I've found numerous resources online discussing this topic, none of them seem to present a method that resonates with me.

My current setup involves a form with multiple inputs that are sent to the server upon clicking a "Submit" button. This data is transmitted through a json request using the conventional AngularJS controller/service, and then processed by my ExpressJS router before being stored in a MongoDB database.

I am looking to include an input for users to select an image file to upload. However, all the solutions I've come across online involve immediately copying the selected file to the server as soon as it's chosen - an approach that doesn't align with my requirements. Is there a way to delay the file upload until the user clicks the "Submit" button? If so, where can I find more information on how to achieve this?

Any help would be greatly appreciated.

Answer №1

Check out this awesome npm package for file uploads: https://www.npmjs.com/package/express-fileupload

I decided to save the file on the filesystem, but it can easily be modified to store it in a MongoDB database.

The router

router.post('/foo', function (req, res, next) {
 if (!req.files){
    res.redirect('/foo');
 }
 let file = req.files.file;
 let fileName = req.files.file.name;
 if(sys.isJSFile(fileName)){
    //save to filesystem or mongodb
    let filePath = path.join('./images', fileName);
    // Use the mv() method to place the file somewhere on your server
    file.mv(filePath, function(err) {
        if (err){
            logger.error("Could not upload file: " + err);
            res.redirect('/foo');
        } else {
            res.redirect('/bar');
        }
    });
});

The view

<form class="form-horizontal" action="/foo" method="post" encType="multipart/form-data">
     <div class="form-group">
         <input class="form-control" type="file" name="file" />
     </div>
     <div class="form-group">
         <input class="form-control" type="submit" value="Submit"/>
     </div>
</form>

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

How can I fill the data array of arrays using an Angular Table component?

I am struggling to populate an Angular Table with data in the array of arrays format. Despite my efforts, the code I have written does not seem to work. Any suggestions for a solution would be greatly appreciated. Here is the data that I am trying to popu ...

A guide on implementing Angular-DataTable within a TypeScript project

Hey everyone, I'm currently working on a TypeScript and Angular application. To create a data table, I decided to use Angular-DataTable. After creating a sample application using it, I added the following code to my Controller: constructor(protecte ...

Filter out all elements that come before the comma in the sorted array's output

Looking for a solution to modify my code so the output is just "Bothell" without the comma and count part. let As = document.getElementsByTagName('a'); let towns = new Map(); for(let a of As) { let town = a.textContent.split(',') ...

What is the best method for transmitting all parameters via a URL?

$(document).ready(function () { $("#submitButton").click(function () { var name = $("#name").val(); var age = $("#age").val(); var gender = $('input:radio[name=gender]:checked').val(); v ...

I am unable to get the documentclient put to work, despite trying all possible

My hashkey is a number labeled pid The following code snippet demonstrates the process: app.get('/register', (req, res) => { var params = { TableName:"passengers", Item: { "pid": 55 } }; console.log("Adding a new item..."); docCl ...

Retrieve the content from paragraph elements excluding any text enclosed within span tags using the Document.querySelector method

Exploring the following element structure: <p> <span class="ts-aria-only"> Departure </span> RUH <span class="ts-aria-only">&nbsp;Riyadh</span> </p> In an attempt to extract the text RUH, it has been disc ...

The behavior of Date's constructor differs when applied to trimmed versus untrimmed strings

Although it's commonly advised against creating a date from a string, I stumbled upon an interesting phenomenon: adding a space before or after the date string can impact the resulting date value. console.log([ new Date('2019-03'), ...

What magic powers the Async Express middleware possesses, I wonder?

My current Express (4.0) setup looks like this: app.get('/api/tracks', (req, res) => { }); Now, I want to implement a request to elasticsearch: app.get('/api/tracks', (req, res) => { client.search({ index: 'so ...

Node-fetch enables dynamic requests

Seeking to retrieve real-time data from a fast-updating API has posed a challenge for me. The issue lies in my code constantly returning the same value. I've experimented with two approaches: var fetch = require("node-fetch"); for(let i=0; i<5; i+ ...

I am currently working on completing my order book code, but I am struggling to understand how to summarize the objects

I have been working on my order book code and I am struggling to figure out how to summarize objects. Below is the current code that I have: const orderbook = [ { "ClientID": "31135d2c-a5f0-11ed-b07a-10e7c6f7c62e", "Side": "BID", ...

Encountering an issue with Server Side Rendering in React Router Dom where an error message pops up saying: "Warning: React.createElement: type is

Specific Error: A warning has occurred: React.createElement: the type provided is invalid -- it was expecting a string (for built-in components) or a class/function (for composite components), but instead received an object. in Posts in Connect(Po ...

Retrieve child and descendant nodes with Fancytree JQuery

I'm currently utilizing Fancytree and have created the following tree structure: root |_ child1 |_ subchild1 |_ subchild2 |_ subchild3 |_ subchild4 When the selected node is child1, I am able to retrieve the fir ...

What is the method for replacing browser bundle sources using Rollup?

Is it possible to use rollup to swap out a specific source with another source in an NPM package when creating a browser bundle? The source in question is loaded dynamically using import('./relativeFile.js') (I need this to be replaced). I attem ...

How can I extract information from Firebase and set it in the this.props of a React component?

Hey there, I'm having some trouble with my Firebase setup. I need to transfer data from snapshot.val() into this.props.device, but when I try to do so within the this.firebaseRef.on() function, 'this' is showing up as 'null'. Any s ...

Add the item to a fresh array using the Ajax function

Here is an array that I have: var arrayOfResults = []; // Results after like statement After making a database call, I receive a JSON result like this: [{ "id": "{fcb42c9c-3617-4048-b2a0-2600775a4c34}", "pid": "{34214CCB-90C3-4D ...

Encountering an issue when trying to install Mongoose via NPM with the error message "Error: gss

Upon executing npm install mongoose --save, a WARNING is generated while working on El Capitan 10.11.1, Xcode 7.1.1 Build version 7B1005, and npm 2.14.7. Although the operation appears functional at the moment, I am curious to delve deeper into this issu ...

Why are my styles not working when referenced from the .module.scss file?

Here is the code snippet from my Sublayout.module.scss file: .pl-6 { padding-left: 6rem !important; } .pr-6 { padding-right: 6rem !important; } .pl-12 { padding-left: 12rem !important; } .pr-12 { padding-right: 12rem !important; } After im ...

organizing data using backbone marionette router

I am attempting to display the query string, but I am only receiving null as output. The query string I am using is http:://localhost/admin/brands?foo=bar and no matter what I try, queryString remains null. I even attempted /brands/?foo=bar with no succes ...

One potential solution is sending a message to a user via a server using JavaScript on Node.js

Hey there, I've encountered a minor issue and would appreciate your help. Recently, I developed a weather program in NodeJs where users can search for the weather in their city. However, I'm facing a challenge with displaying the weather data to ...

The jQuery ajax request was unsuccessful in connecting to the remote server

I've tried researching and troubleshooting, but I still can't figure out why the Ajax code is not functioning correctly. Here is my JavaScript code: $(document).ready(function(){ $("#tform").submit(function() { var varUserName ...