Я реализую веб-приложение, используя MEAN Stack и Angular 6. Там я хочу отправить форму с загрузкой файла. Файлы .png должны быть загружены. Я хочу сохранить файл на другом файловом сервере и отправить URL-адрес изображения. В настоящее время я загружаю файлы в папку в своем проекте и сохраняю изображение в базе данных. Тогда это сохраняет как это. "Данные: изображение / PNG; base64, iVBORw0KGgoAAAANSUhEUgAAAV4AAAFUCAYAAABssFR8AAAK ..."
Но я хочу сохранить URL-адрес изображения в mongodb, и изображение должно быть восстановлено по URL-адресу. Я следовал этому методу. Как вернуть URL изображения, используя multer
var mapInfo = require('../../../models/mongoModels/map');
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads/')
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now() + '.png')
}
})
var upload = multer({ storage: storage, limits: { fileSize: 524288 } });
router.post('/uploadMap', upload.single('milespecMap'), function (req, res, next) {
//var imageName = req.file.filename;
var path = req.file.filename;
console.log("file Name is"+req.file.filename);
console.log("file path is"+req.file.path);
//res.send(imageName);
res.end(this.path);
});
//Save or update map
router.post("/update", function (req, res) {
var mod = new mapInfo(req.body);
mapInfo.findOneAndUpdate(
{
mapName: req.body.mapName,
},
req.body,
{ upsert: true, new: true },
function (err, data) {
if (err) {
console.log(err);
res.send(err);
} else {
// console.log(res);
res.send(mod);
}
}
);
});
module.exports = router;
Это моя схема.
// Schema
var mapSchema = new mongoose.Schema({
mapName: {
type: String,
},
milespecUrl: {
type: String,
},
});
module.exports = mongoose.model ('mapData', mapSchema);
Это мой .ts файл
export class MapsComponent implements OnInit {
closeResult: string;
currentMapDetails: Map = new Map();
selectedFile: File = null;
public uploader: FileUploader = new FileUploader({ url: URL, itemAlias: 'milespecMap', });
constructor(private modalService: NgbModal,
private mapsService: MapsService,
private http: Http,
private router: Router
) { }
ngOnInit() {
}
openModal(content: any) {
this.modalService.open(content).result.then((result) => {
this.closeResult = `Closed with: ${result}`;
}, (reason) => {
this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
});
}
private getDismissReason(reason: any): string {
if (reason === ModalDismissReasons.ESC) {
return 'by pressing ESC';
} else if (reason === ModalDismissReasons.BACKDROP_CLICK) {
return 'by clicking on a backdrop';
} else {
return `with: ${reason}`;
}
}
handleFileInput(file: FileList) {
this.selectedFile = file.item(0);
var reader = new FileReader();
reader.onload = (event: any) => {
**this.currentMapDetails.milespecUrl = event.target.result;**
console.log(reader.onload);
}
reader.readAsDataURL(this.selectedFile);
}
updateInfo() {
this.uploader.uploadAll(); ///image upload
this.update();
}
update() {
console.log(this.currentMapDetails);
this.mapsService.updateMap(this.currentMapDetails).subscribe(res => {
this.currentMapDetails;
console.log(res);
}, (err) => {
console.log(err);
});
console.log(this.currentMapDetails);
}
}
Это релевантная HTML-часть.
<div class="input-group">
<input type="file" class="form-control" #fileInput name="milespecMap" ng2FileSelect [uploader]="uploader" (change)="handleFileInput($event.target.files)"
/>
</div>
Сохранение выполняется в функции update (). Жирная часть сохраняет изображение вместо URL. Вместо этого я хочу установить URL-адрес местоположения изображения в переменную 'milespecUrl'. Я могу получить URL-адрес с помощью 'req.file.path' на заднем плане. Я хочу использовать его в файле component.ts для установки 'milespecUrl'. У кого-нибудь есть идея?