我有一个表格要求Angular中的pdf文件的详细信息。我想将该文件上传到PDFS文件夹,而不是数据库。所以在这里我想做三件事:
tech:Angular,express,MongoDB,mulatto
如果已经提供了所有这些条件的示例,您可以为我提供链接。
这是快递节点和mongo端,用于将文件保存到快速服务器本地的文件夹中。路径会
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const DIR = path.join(__dirname, '../PDFS/');
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, DIR);
},
filename: (req, file, cb) => {
// implement getLoggedInUser() method which basically returns the current logged in user
cb(null, file.fieldname + '-' + Date.now()+ getLoggedInUser())
},
});
//upload end point
app.post('/upload', upload.array('uploads[]', 12), (req, res) => {
console.log(req.files);
if (req.files.length <= 0) {
res.status(404).send({ message: 'no file recieved' });
} else {
fs.readdirSync(DIR).forEach((file)=>{
let path=path.join(DIR,file);
let fileSchema= new FileSchema(path);
fileSchema.save((err,result)=>{
if (err) {
throw new Error({ message: 'user is not saved', status: 500 });
}
res.status(200).send({ message: 'file successfully saved' });
});
});
}
});
从角度应用程序中,您可以创建服务并将其注入表单组件中
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpClient, HttpHeaders } from '@angular/common/http'
import { map } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class UploadService {
static API_URL: string = '<url for your upload end point>';
constructor(private http: HttpClient) { }
fileUpload(files: any): Observable<Object> {
const formData: any = new FormData();
const fileArray: Array<File> = files;
for (let i = 0; i < fileArray.length; i++) {
formData.append('uploads[]', fileArray[i], fileArray[i]['name']);
}
return this.http.post(UploadService.API_URL + 'upload', formData)
.pipe(
map(x => {
return x;
})
);
}
}