1

I am facing problem while uploading multiple files in angular, node, multer. Last file in array is uploaded to server.

Here is my HTML.

<div class="mb-1">
    <p class="text-muted m-0">Anti Black List</p>
    <input type="file"  (change)="fileChangeEvent($event)" name="Anti Black List" id="4" #fileDataAntiBlackList (onFileSelected)="onFileSelected($event ,fileDataAntiBlackList)" ng2FileSelect [uploader]="uploader"  accept="application/pdf"/>  
  </div>
<div class="mb-1">
    <p class="text-muted m-0">Anti Black List</p>
    <input type="file"  (change)="fileChangeEvent($event)" name="Shop Act" id="3" #fileDataShopAct (onFileSelected)="onFileSelected($event ,fileDataShopAct)" ng2FileSelect [uploader]="uploader"  accept="application/pdf"/>  
  </div>
<div class="mb-1">
    <p class="text-muted m-0">Anti Black List</p>
    <input type="file"  (change)="fileChangeEvent($event)" name="Professional Tax" id="2"  #fileDataPRO (onFileSelected)="onFileSelected($event ,fileDataPRO)" ng2FileSelect [uploader]="uploader"  accept="application/pdf"/>  
  </div>
<div class="mb-1">
    <p class="text-muted m-0">Anti Black List</p>
    <input type="file"  (change)="fileChangeEvent($event)" name="GST Copy" id="1" #fileDataGST (onFileSelected)="onFileSelected($event ,fileDataGST)" ng2FileSelect [uploader]="uploader"  accept="application/pdf"/>  
  </div>
<mat-label>First name</mat-label>
    <input formControlName="f_name" matInput type="text" name="first_name" placeholder="First name"  required/>
<mat-label>Last name</mat-label>
    <input formControlName="l_name" matInput type="text" name="Last_name" placeholder="Last name" required/>
<button mat-raised-button color="primary" class="mx-4" (click)="onSubmit()"
        [disabled]="uploader.getNotUploadedItems().length && signupForm.invalid">Upload And Save </button>

There are more fields, but i have shown less here.

Following is TS file code

filesToUpload: Array<File> = [];
fileChangeEvent(fileInput: any) {
this.filesToUpload = <Array<File>>fileInput.target.files;
//this.product.photo = fileInput.target.files[0]['name'];
}
onSubmit() {
//let files = this.getFiles();
let dbId: number;
let formData = new FormData();
const files: Array<File> = this.filesToUpload;
for(let i = 0; i < files.length;i++){
  formData.append("files", files[i], files[i]['name']);
}
formData.append('first_name',this.signupForm.value.f_name);
 this.http.post('http://localhost:3000/api/newUpload', formData)
    .map(files => files)
    .subscribe(files => console.log('files', files));
    return false;
}

This is my backend API Upload

let user_storage = multer.diskStorage({
destination: (req, file, cb) => {
    cb(null, DIR);
},
filename: (req, file, cb) => {
    cb(null, file.fieldname + '-' + Date.now() + '' + path.extname(file.originalname));
}
});
let upload = multer({ storage: user_storage }).array('files',10);

API function

router.post('/newUpload',function(req,res){
console.log('before upload',req.body);
upload(req,res,function(err) {
    //console.log(req.body);
    //console.log(req.files);
    if(err) {
        return res.end("Error uploading file.");
    }
    console.log('files', req.files);
    console.log(req.body);
    res.send(req.files);
    //res.end("File is uploaded");
});
});

This is what i have tried. Only last file in array is save in uploads folder. Also i want to insert first name , last name etc to database but when i console req.body is gives empty json {}

Edit quetion i got where i am missing. Its in angular code : when i print

const files: Array<File> = this.filesToUpload;

i get last file which i uploaded. means it takes last file which is uploaded not all files. so i use following function

getFiles(){
return this.uploader.queue.map((fileItem) => {
      return fileItem.file;
   });
}

So in onsubmit function

onSubmit() {
let files = this.getFiles();
let formData = new FormData();
for(let i = 0; i < files.length;i++){
  console.log(files[i]);
  formData.append("files", files[i],files[i]['name']);
}

When i console files[i], get all files. But in line formData.append line i get following error

Argument of type 'FileLikeObject' is not assignable to parameter of type 'string | Blob'.
Property 'slice' is missing in type 'FileLikeObject' but required in type 'Blob

P.S : when i send file name in formdata.append, i get all file names in node serevr.

2 Answers 2

1

After trying different solutions, finally i got working solutions by which multiple files and other input fields are also send to sever.

In my Edit part of question, i have use following function

getFiles(){
return this.uploader.queue.map((fileItem) => {
  return fileItem.file;
});
}

above code was giving error. I have just changed return line.

from

return fileItem.file;

to

return fileItem.file.rawFile;

Thats it. All remaining code is same as in edit.

Sign up to request clarification or add additional context in comments.

Comments

0

you forget to add multer middleware to your router.post it should be

outer.post('/newUpload',
    upload.array('myFiles', 12),
    function(req,res){
    upload(req,res,function(err) {

   if(err) {
        return res.end("Error uploading file.");
    }
    res.send(req.files);
    //res.end("File is uploaded");
});
});

4 Comments

You can see in my code let upload = multer({ storage: user_storage }).array('files',10); i have used array. btw i have tried your code, still i am facing same problem. It uploads last file in array.
when you are appending to the form data try to do ``` formData.append("files[]", files[i], files[i]['name']); ``` instead of ``` formData.append("files", files[i], files[i]['name']); ```
you can read more about FormData usage here developer.mozilla.org/en-US/docs/Web/API/FormData/append
when i use formData.append("files[]", files[i], files[i]['name']); i get error MulterError: Unexpected field this error occur because filed name and name in multer is diffrent

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.