我正在尝试将文件上传到NAS /网络共享路径/远程服务器。下面是我上传文件的角度代码。
//My component code upload method
upload() {
//locate the file element meant for the file upload.
let inputEl: HTMLInputElement = this.el.nativeElement.querySelector('#txtUpload');
//get the total amount of files attached to the file input.
let fileCount: number = inputEl.files.length;
//create a new fromdata instance
let formData = new FormData();
//check if the filecount is greater than zero, to be sure a file was selected.
if (fileCount > 0) { // a file was selected
formData.append('uploadedFile', inputEl.files.item(0));
this.fileUploadService.uploadFile(formData).subscribe(res=>{
console.log(res);
});
}
}
<!--my HTML code-->
<input id="txtUpload" type="file" class="form-control"/>
<button type="button" class="btn btn-success btn-s" (click)="upload()">
Upload
</button>
Upload方法正在调用角度服务,该角度服务在内部调用express API。
下面是我API中的代码。
var express =require('express');
var router=express.Router();
var multer=require('multer');
var fs = require('fs');
var tempDir='./uploads/';
//my shared path is in this format.
var sharedPath='\\\\mycomputer.abc.com\\Upload\\Files\\';
//multer module disk storage
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, tempDir)
},
filename: function (req, file, cb) {
cb(null, renameFile(file.originalname))
}
})
var upload = multer({storage: storage}).single('uploadedFile');
//upload file to shared path
router.post('/', function (req, res, next) {
//upload is multer function which will store file in temp path
upload(req, res, function (err) {
if (err) {
console.log(err);
return res.status(422).send('temporary file store failed.');
}
else{
//Read file from temparory path
fs.readFile(req.file.path,function(err,data){
if(err){
console.log(err);
res.status(422).send('file read from temporary path failed.');
}
else{
console.log(data);
//write file to shared path
fs.writeFile(sharedPath+req.file.filename,data,function(err){
if(err){
console.log(err);
res.status(422).send('file write to remote server path failed.');
}
else{
res.send({file:req.file});
}
})
}
});
}
});
})
function renameFile(originalFileName){
let lastIndex=originalFileName.lastIndexOf('.');
let fileName=originalFileName;
let fileExtension='';
if(lastIndex>-1)
{
fileName=originalFileName.substring(0,lastIndex);
fileExtension=originalFileName.substring(lastIndex);
}
return fileName+'-'+Date.now()+fileExtension;
}
module.exports = router;
在API代码中,我正在使用Multer包将文件上传到运行API的服务器上。使用fs.FileRead将该读取文件发布,然后使用fs.writeFile将文件写入NAS或共享路径。
此代码在我的本地计算机上正常工作。
但是,当我使用Cloud Foundry部署代码时,未在共享路径上创建文件。我没有任何错误。代码没有失败,但是也没有在共享路径上创建文件。 有什么建议我该怎么办?
更新: 忘了提到我的机器上装有Windows 10。 cloud Foundry创建Linux虚拟机来托管API。 另外,我正在使用nodejs_buildpack来为Cloud Foundry重新构建。