Saving uploaded files to a folder using ngFileUpload and Multer

I am brand new to angular MEAN and I am currently attempting to upload a file, specifically a PDF, and save it to the server. Despite my efforts, I have been unable to locate any examples on how to actually save the uploaded file to the server's storage.

In this project, I am utilizing the ng-file-upload directive from https://github.com/danialfarid/ng-file-upload, Express for the server, and AngularJS for the file upload functionality.

POST UPDATED!! Please see below

Additional information: For this project, I am using Yeoman's full mean stack generator.

UPDATE: I attempted to use multer (https://github.com/expressjs/multer) to save the uploaded file to the server. However, when trying to upload the file, I encountered a 500 error with the following message:

Error: Unexpected field
   at makeError ({proj_folder}/node_modules/multer/lib/make-error.js:12:13)
   ...

Updated HTML

<form accept-charset="UTF-8" class="form" name="form" ng-submit="$ctrl.submitForm(form)" 
                enctype="multipart/form-data">
...
<input ngf-select ng-model="$ctrl.paperFile" ngf-model-options="{allowInvalid: true}" name="paper" ngf-accept="'application/pdf'" required="" type="file" >
...
</form>

submitForm method

...
    this.Upload.upload({
            url:'/paperUpload',
            method: 'POST',
            file: this.paperFile,
            fields:{
              _id:this.user._id
            }
          })
          .then(function(resp){
             console.log('Success upload');
             console.log(resp.data);
          }, function(error){
            console.log('fail upload');
            console.log(error);
          }, function(evt){
            console.log('upload on progress');
            console.log(evt);
          });

Server route:

var express = require('express');
var multer = require('multer');
var router = express.Router();
var upload = multer({dest:'uploads/',
    rename: function(fieldname, filename){
        return filename+"_"+Date.now(); 
    }});
router.post('/paperUpload', upload.single('paper'), uploadPaper);

...

//method to upload
export function uploadPaper(req,res){
  res.status(204).end();
}

Although the 'uploads' folder is created, the file is not being uploaded and consistently results in failure.

Any assistance would be greatly appreciated. Thank you

Answer №1

Follow these instructions:

  1. Start by running npm install ng-file-upload
  2. Add ng-file-upload.min.js to your Angular index .html file
  3. To implement file upload functionality in your Angular app, use this example code from http://jsfiddle.net/0m29o9k7/. Copy and paste the code provided outside of any existing form on your page:

  4. Modify the URL in the example code to specify where you want to upload files -- url: '',

  5. In your server.js or app.js (depending on what you're using to run your app), include the following lines:

    var crypto = require('crypto'); var mime = require('mime'); var multer = require('multer');

    var storage = multer.diskStorage({
      destination: function (req, file, cb) {
        cb(null, 'app/app-content/images/')
      },
      filename: function (req, file, cb) {
        crypto.pseudoRandomBytes(16, function (err, raw) {
          cb(null, raw.toString('hex') + Date.now() + '.' + mime.extension(file.mimetype));
        });
      }
    });
    
    var upload = multer({ storage: storage });
    
    // set '/app' as the default route
    app.post('/', upload.any(), function (req, res) { 
        res.send(req.files);
    });
    

Customize the 'app/app-content/images/' path to specify the location where uploaded files will be stored

This code configures the file upload URL to point to your Node server's root directory, allowing you to easily access the uploaded files.

Answer №2

Have you tried using the 'file' or 'fields' options with Upload.upload before? I recently encountered a similar issue and was able to resolve it by including the arrayField in my POST request. If you encounter the same error, consider removing 'fields' and instead adding a new key to the data object with the _id that needs to be passed.

this.Upload.upload({
            url:'/paperUpload',
            method: 'POST',
            headers: {
                'Content-Type': 'multipart/form-data ; boundary = ----WebKitFormBoundaryvlb7BC9EAvfLB2q5'
            },
            arrayKey: '',
            data: {
              paper: this.paperFile,
            },
            fields:{
              _id:this.user._id
            }
          })
          .then(function(resp){
             console.log('Success upload');
             console.log(resp.data);
          }, function(error){
            console.log('fail upload');
            console.log(error);
          }, function(evt){
            console.log('upload on progress');
            console.log(evt);
          });

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

Transferring Information from Vue to PHP: What You Need to Know

I need assistance with passing data from Vue to PHP. Currently, I receive a JSON object through a PHP query that looks like this: <?php echo getBhQuery('search','JobOrder','isOpen:true','id,title,categories,dateAdded, ...

The dynamic JavaScript in Bootstrap 4 seems to be malfunctioning, despite working perfectly in Bootstrap 3

I am currently implementing a dynamic modal feature using the code snippet below: // Show Ajax modal with content $(document).on('click', '[data-modal]', function (event) { event.preventDefault(); $.get($(this).data('moda ...

Issue with Angular UI-Grid: Tooltip not appearing

I'm having trouble implementing a filter on ui-grid cells while also adding a tooltip. The filter works fine, but the tooltip does not display unless I remove the filter. cellFilter: 'number: 2', cellTooltip: 'Custom tooltip - maybe som ...

The v-on handler is encountering an error: "ReferenceError: i18n is not defined"

I'm currently working on a Vue.js project to create a multi-language website, but I'm struggling with how to access and utilize the i18n constant. I've attempted using the eventBus approach, but it doesn't seem to be the right solution ...

Sort an array of numbers with orderBy and ensure any string values are placed at the end

After spending some time working on this issue, I have decided to share my problem and its solution here in case it can help someone else. I encountered a challenge when trying to sort the array below by duration in descending order: { 0: { first ...

Exploring the world of audio playback in TypeScript/JavaScript and Electron using setInterval

I am currently developing a metronome using electron, and I am playing the audio through howler. When the window is active on the screen, the audio plays correctly. However, when I minimize the window, the audio starts to play at incorrect intervals causi ...

Data in DynamoDB Local is deleted once the instance is shut down

My app is utilizing DynamoDB Local and I am facing an issue where it keeps deleting all the sample data each time I shut down the instance. This problem seems to be unique as I have not found any similar cases while searching for a solution. I typically ...

Flawless 2D mouse selection using Canvas for pixel-perfect accuracy

Currently, I am developing a 2D game in HTML5 using Canvas that requires precise detection of mouse click and hover events. The main challenges I am facing include the need for pixel-perfect detections, working with non-rectangular objects such as houses a ...

Choose an option with JavaScript once the request is successful

Choose the day, month, and year using JSON data success: function(jsondata){ var data=JSON.parse(jsondata); var list_html="<div id='editrelation'><label id='dateLabel' style='display:none&apo ...

Issue persists with Angular 2 *ngFor functionality even after successfully importing CommonModule

After creating a feature module using the CLI, I imported the common module as shown below: import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { HomeComponent } from './home/home.compo ...

React fetch request does not reach the Express router's index route

Having some experience with Express, I am relatively new to React. My React app is connected to an Express server, but I am struggling to get fetch('/') in my main React App component to hit the index route in Express. In my Express app, I have s ...

establish the reliance on field w

I want to create a dependency between two fields. The selectbox contains a list of options. If the first or fifth option is selected in the dropdownbox, apply the class "selectboxlist". Then I would like to set the value '-1' in the second ...

Struggling with incorporating elements into a dynamic CSS3 banner design?

Struggling to add up to 10 text items to the CSS3 animated banner. Having difficulty getting the items to display properly. I'm curious if there is a simpler way to achieve this with animations as shown in this example: http://jsfiddle.net/zp6B8/1/ & ...

The useTransition() method in React remains stuck in the isPending state when making API calls from routes in the /pages/api directory

I'm encountering an issue with the useTransition() function where it remains true and never changes back to false. I am attempting to delete a record from MongoDB and after completion, I want to refresh the React Server Component following the guideli ...

Is it possible to create a React Component without using a Function or Class

At times, I've come across and written React code that looks like this: const text = ( <p> Some text </p> ); While this method does work, are there any potential issues with it? I understand that I can't use props in this s ...

Design a slider that mimics infinite scrolling using CSS

I am attempting to design a CSS slider with infinite scroll functionality, but I want to achieve this without the need to dynamically add or manipulate DOM elements. The goal is for the slider to loop back to the first slide when the last one is reached. ...

Tips for turning off server-side sorting in Datatables

Following up on my previous question here, I am utilizing Datatables with server-side processing. $('#dataTables1').DataTable({ "bProcessing": true, "bPaginate": false, "serverSide": true, "ajax":{ ...

The property 'x' cannot be found when declaring two different return types

Consider this example: interface Dog { name: string } const likeDog = true const getDog = (): Dog | boolean => { const val = likeDog ? { name: 'fido' } : false return val } const myComponent = (): void => { const dog = getDog() ...

Remove all nested object entries

In my coding project, I have a class structure defined as follows: class Foo{ id:string; name:string; childFooIds: string[]; } Within this structure, each instance of Foo can reference its child Foo objects by ID. These Foo instanc ...

When an HTML input button within a table fails to trigger any jQuery function upon being clicked

I currently have a table set up with multiple rows and columns. <table style="width: 100%;" class='table_result'> <tr><td>Text</td><td>Text</td><td>Text</td><td>Text</td> ...