2017-03-06 85 views
1

我想從Angular 2和Sails Js服務器上傳多個文件。我想將文件放入SailJs App的公共文件夾中。文件上傳Angular 2&Sails Js

該文件是從Angular 2應用程序通過從事件中獲取文件上傳。對於單文件上傳的代碼如下:

角2服務:

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方法:

/** 
    * `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() 
     }); 
    }); 
    }, 

形式發佈後,我並沒有在HTTP呼叫響應獲取文件還不能夠console.log(req.param('filename'));

請幫助我在這裏做錯了什麼。我也試過改變/去除頭,但仍然沒有工作,

一些專家說,目前HTTP着上傳文件,需要使用本機XHR請求這一點。請查看Thierry Templier的回答here

回答

0

嘗試指定一個目錄文件上傳:

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); 
    }); 

要訪問上傳的文件 - 你可以追加文件名到您指定的上傳目錄。文件將被訪問