2

I am trying to upload multiple files from Angular 2 and Sails Js server. I want to place file inside public folder of SailJs App.

The file is uploaded from Angular 2 App by getting file from an event fired. the code for single file upload is as follows:

Angular 2 service:

fileChange(event: any): Promise<string>  {
    let fileList: FileList = event.target.files;
    if(fileList.length > 0) {
        let file: File = fileList[0];
        let formData:FormData = new FormData();
        formData.append('myFile', file, file.name);
        let headers = new Headers();
        let cToken = this.cookie.getCookie("token");
        headers.append('Authorization', 'Bearer ' + cToken);
        headers.append('Content-Type', undefined);

        //headers.append('Content-Type', 'multipart/form-data');

        headers.append('Accept', 'application/json');
        let options: RequestOptionsArgs = { headers: headers, withCredentials: true }
        return new Promise((resolve, reject) => {
            this.http.post( this.apiEndpoint + "project/reffile/add/all", formData, options).toPromise()
            .then(response => {
                // The promise is resolved once the HTTP call is successful.
                let jsonData = response.json();
                if (jsonData.apiStatus == 1) {
                    resolve(jsonData);
                }
                else reject(jsonData.message);
            })
            // The promise is rejected if there is an error with the HTTP call.
            // if we don't get any answers the proxy/api will probably be down
            .catch(reason => reject(reason.statusText));
        });
    }
}

SailsJs method:

  /**
   * `FileController.upload()`
   *
   * Upload file(s) to the server's disk.
   */
   addAll: function (req, res) {

    // e.g.
    // 0 => infinite
    // 240000 => 4 minutes (240,000 miliseconds)
    // etc.
    //
    // Node defaults to 2 minutes.
    res.setTimeout(0);

    console.log("req.param('filename')");
    console.log(req.param('filename'));
    req.file('myFile')
    .upload({

      // You can apply a file upload limit (in bytes)
      maxBytes: 1000000

    }, function whenDone(err, uploadedFiles) {
      if (err) return res.serverError(err);
      else return res.json({
        files: uploadedFiles,
        textParams: req.allParams()
      });
    });
  },

after posting form, I didn't get file in HTTP call response also not able to console.log(req.param('filename'));.

please help me what I am doing wrong here. I also tried changing/removing header, but still not working,

some expert says that HTTP currently cant upload files, need to use native XHR request for this. please view Thierry Templier's answer here

Community
  • 1
  • 1
Kaleem Ullah
  • 6,799
  • 3
  • 42
  • 47

1 Answers1

0

Try specifying a directory for file upload:

    req.file('file').upload({
        dirname: '../../assets/uploads'
    },function (err, files) {
        if (err) return res.serverError(err);
        var fileNameArray = files[0].fd.split("/");
        var fileName = fileNameArray[fileNameArray.length - 1];
        console.log("fileName: ",fileName);
    });

To access the uploaded file - you can append the fileName to the upload directory that you have specified. File will be accessible

Paritosh Gupta
  • 306
  • 3
  • 5