我正在尝试上传文件
home.html的
<h3>File Upload</h3>
<div>
Select file:
<input type="file" (change)="psdTemplateSelectionHandler($event)" name="userPhoto">
</div>
<input type="button" value="click" (click)="psdTemplateUploadHandler()" />
homecomponent.ts
import {Component, View, Inject} from 'angular2/core';
import {FileUploadService} from '../../services/fileUploadService';
@Component({
selector: 'home',
providers: [FileUploadService]
})
@View({
templateUrl: '/scripts/src/components/home/home.html',
})
export class HomeComponent {
psdTemplates: any;
constructor( @Inject(FileUploadService) private fileUploadService: FileUploadService) {
this.psdTemplates = new Array<File>();
}
public psdTemplateSelectionHandler(fileInput: any) {
console.log(fileInput);
let FileList: FileList = fileInput.target.files;
for (let i = 0, length = FileList.length; i < length; i++) {
this.psdTemplates.push(FileList.item(i));
}
console.log(this.psdTemplates);
// this.progressBarVisibility = true;
}
public psdTemplateUploadHandler() {
let result: any;
if (!this.psdTemplates.length) {
return;
}
this.fileUploadService.getObserver()
.subscribe(progress => {
console.log(progress)
});
try {
result = this.fileUploadService.upload('/upload', this.psdTemplates);
} catch (error) {
document.write(error)
}
console.log(result);
if (!result['images']) {
return;
}
// this.saveUploadedTemplatesData(result['images']);
}
}
FileUploadService
import { Component } from 'angular2/core';
import { Injectable } from 'angular2/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/share';
@Injectable()
export class FileUploadService {
/**
* @param Observable<number>
*/
private progress$: Observable<number>;
/**
* @type {number}
*/
private progress: number = 0;
private progressObserver: any;
constructor () {
this.progress$ = new Observable(observer => {
this.progressObserver = observer
});
}
/**
* @returns {Observable<number>}
*/
public getObserver (): Observable<number> {
return this.progress$;
}
/**
* Upload files through XMLHttpRequest
*
* @param url
* @param files
* @returns {Promise<T>}
*/
public upload (url: string, files: File[]): Promise<any> {
return new Promise((resolve, reject) => {
let formData: FormData = new FormData(),
xhr: XMLHttpRequest = new XMLHttpRequest();
for (let i = 0; i < files.length; i++) {
formData.append("uploads[]", files[i], files[i].name);
}
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
resolve(JSON.parse(xhr.response));
} else {
reject(xhr.response);
}
}
};
FileUploadService.setUploadUpdateInterval(500);
xhr.upload.onprogress = (event) => {
this.progress = Math.round(event.loaded / event.total * 100);
this.progressObserver.next(this.progress);
};
xhr.open('POST', url, true);
xhr.send(formData);
});
}
/**
* Set interval for frequency with which Observable inside Promise will share data with subscribers.
*
* @param interval
*/
private static setUploadUpdateInterval (interval: number): void {
setInterval(() => {}, interval);
}
}
服务器端代码
var storage = multer.diskStorage({
destination: function(req, file, callback) {
console.log(file);
callback(null, '../uploads');
},
filename: function(req, file, callback) {
console.log(file);
callback(null, file.fieldname + '-' + Date.now() + '.' + file.originalname.split('.')[1]);
}
});
var upload = multer({ storage: storage }).single('userPhoto');
app.post("/upload", function(req, res) {
upload(req, res, function(err) {
console.log(req.files);
console.log(err);
if (err) {
return res.end({ status: 'Error uploading file' });
}
res.end({ status: "File is uploaded" });
});
});
但是当我上传文件时会给出错误
这里是我的请求电话
请帮我纠正
答案 0 :(得分:1)
请看这个代码,这个代码对我有用 服务: -
import { Component } from 'angular2/core';
import { Injectable } from 'angular2/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/share';
@Injectable()
export class FileUploadService {
/**
* @param Observable<number>
*/
private progress$: Observable<number>;
/**
* @type {number}
*/
private progress: number = 0;
private progressObserver: any;
constructor () {
this.progress$ = new Observable(observer => {
this.progressObserver = observer
});
}
/**
* @returns {Observable<number>}
*/
public getObserver (): Observable<number> {
return this.progress$;
}
/**
* Upload files through XMLHttpRequest
*
* @param url
* @param files
* @returns {Promise<T>}
*/
public upload (url: string, files: File[]): Promise<any> {
return new Promise((resolve, reject) => {
let formData: FormData = new FormData(),
xhr: XMLHttpRequest = new XMLHttpRequest();
for (let i = 0; i < files.length; i++) {
formData.append("uploads", files[i], files[i].name);
}
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
resolve(JSON.parse(xhr.response));
} else {
reject(xhr.response);
}
}
};
FileUploadService.setUploadUpdateInterval(500);
xhr.upload.onprogress = (event) => {
this.progress = Math.round(event.loaded / event.total * 100);
this.progressObserver.next(this.progress);
};
xhr.open('POST', url, true);
xhr.send(formData);
});
}
/**
* Set interval for frequency with which Observable inside Promise will share data with subscribers.
*
* @param interval
*/
private static setUploadUpdateInterval (interval: number): void {
setInterval(() => {}, interval);
}
}
组件文件: -
import {Component, View, Inject} from 'angular2/core';
import {FileUploadService} from '../../services/fileUploadService';
@Component({
selector: 'home',
providers: [FileUploadService]
})
@View({
templateUrl: '/scripts/src/components/home/home.html',
})
export class HomeComponent {
psdTemplates: any;
status: number;
constructor( @Inject(FileUploadService) private fileUploadService: FileUploadService) {
this.psdTemplates = new Array<File>();
}
public psdTemplateSelectionHandler(fileInput: any) {
console.log(fileInput);
let FileList: FileList = fileInput.target.files;
this.psdTemplates.length = 0;
for (let i = 0, length = FileList.length; i < length; i++) {
this.psdTemplates.push(FileList.item(i));
}
console.log(this.psdTemplates);
// this.progressBarVisibility = true;
}
public psdTemplateUploadHandler() {
let result: any;
if (!this.psdTemplates.length) {
return;
}
this.fileUploadService.getObserver()
.subscribe(progress => {
console.log(progress);
this.status = progress;
});
try {
result = this.fileUploadService.upload('/upload', this.psdTemplates).then((res) => {
console.log(res);
}, (err) => { console.log(err); });
} catch (error) {
document.write(error)
}
console.log(result);
if (!result['images']) {
return;
}
// this.saveUploadedTemplatesData(result['images']);
}
}
html: -
<h3>File Upload</h3>
<div>
Select file:
<input type="file" (change)="psdTemplateSelectionHandler($event)" name="userPhoto">
</div>
<input type="button" value="click" (click)="psdTemplateUploadHandler()" /> {{status}}
服务器端: -
var storage = multer.diskStorage({
destination: function(req, file, callback) {
console.log(file);
callback(null, './public/images');
},
filename: function(req, file, callback) {
console.log(file);
callback(null, file.fieldname + '-' + Date.now() + '.' + file.originalname.split('.')[1]);
}
});
var upload = multer({ storage: storage }).single('uploads');
app.post("/upload", function(req, res) {
upload(req, res, function(err) {
if (err) {
return res.send({ status: 'Error uploading file' });
}
res.send({ status: "File is uploaded" });
});
});