我有一张表格,要求在Angular中获取pdf文件的详细信息。我想将该文件上传到 PDFS 文件夹,而不是数据库。所以在这里我想做三件事:
技术:Angular,Express,MongoDB,multer
如果在所有这些条件下都可以使用任何示例,则可以提供一个链接。
答案 0 :(得分:0)
这是Express节点和mongo端,用于将文件保存到Express服务器中本地的文件夹中。路径将
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' });
});
});
}
});
从您的angular应用程序中,您可以创建服务并将其注入到表单组件中
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;
})
);
}
}