gpt4 book ai didi

node.js - Angular2 ExpressJs - 文件上传到服务器

转载 作者:可可西里 更新时间:2023-11-01 10:42:12 27 4
gpt4 key购买 nike

Angular-2 我正在尝试将文件上传到服务器。以下代码将文件上传到服务器,

如何链接到我的 mongodb 文档?上传文件时,我想将其链接到特定文档。

另外,如何在 UI 中提供链接以从服务器下载上传的文件?

组件.ts

@Component({
selector: 'aptcontent',
template: `
<div> <input type="file" (change)="fileChangeEvent($event)" placeholder="Upload file..."></div>

<div >
<a (click)="upload()">Upload Docs</a>
</div>

`,

directives: [ROUTER_DIRECTIVES]
})

export class AptContentComponent implements OnInit {

data: any;
filesToUpload: Array<File>;

constructor(private apartmentService: ApartmentService, private sharedService: SharedService, params: RouteParams) {
this.filesToUpload = [];
}


ngOnInit() {}

upload(){
console.log('upload button clicked');

this.makeFileRequest("http://localhost:3000/upload", [], this.filesToUpload).then((result) => {
console.log(result);
}, (error) => {
console.error(error);
});
}

fileChangeEvent(fileInput: any){
this.filesToUpload = <Array<File>> fileInput.target.files;
}

makeFileRequest(url: string, params: Array<string>, files: Array<File>) {
return new Promise((resolve, reject) => {
var formData: any = new FormData();
var xhr = new XMLHttpRequest();
for(var i = 0; i < files.length; i++) {
formData.append("uploads[]", files[i], files[i].name);
}
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
resolve(JSON.parse(xhr.response));
} else {
reject(xhr.response);
}
}
}
xhr.open("POST", url, true);
xhr.send(formData);
});
}
}

服务器.ts

app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});


app.post("/upload", multer({dest: "./uploads/"}).array("uploads[]", 12), function(req, res) {});

代码在服务器上创建一个上传文件夹,并转储文件类型为 .File 的文件,这不是实际上传的 .jpg 文件。

最佳答案

我正在尝试做同样的事情,这是我的解决方案(不确定这是否是最好的方法),

服务器 js:

var formidable = require('formidable');
var fs = require('fs');

app.post('/upload', function(req, res){

var form = new formidable.IncomingForm();

form.multiples = false;

form.uploadDir = path.join(__dirname, '/public/uploads');


form.on('file', function(field, file) {
fs.rename(file.path, path.join(form.uploadDir, file.name));
});

form.on('error', function(err) {
console.log('An error has occured: \n' + err);
});

form.on('end', function() {
res.end('success');
});

form.parse(req);

});

应用程序组件:

import { Component, OnInit, NgZone } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: 'js/app/app.component.html'
})
export class AppComponent {
filesToUpload: Array<File>;

constructor() {
this.filesToUpload = [];
}

upload() {
this.makeFileRequest("http://localhost:3000/upload", [], this.filesToUpload).then((result) => {
console.log(result);
}, (error) => {
console.error(error);
});
}

fileChangeEvent(fileInput: any){
this.filesToUpload = <Array<File>> fileInput.target.files;
}

makeFileRequest(url: string, params: Array<string>, files: Array<File>) {
return new Promise((resolve, reject) => {
var formData: any = new FormData();
var xhr = new XMLHttpRequest();

for(var i = 0; i < files.length; i++) {
formData.append("uploads[]", files[i], files[i].name);
}

xhr.open("POST", url, true);
xhr.send(formData);
});
}

}

}

注意:这里使用的是 formidable 而不是 multer

关于node.js - Angular2 ExpressJs - 文件上传到服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37761204/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com