我做了一个普通的栈板,效果很好。 (angular2 +,node.js,express,mongoDB)
在我尝试添加上传功能后,它不起作用。 这是错误消息。
compiler.js:486 Uncaught Error: Template parse errors:
Can't bind to 'uploader' since it isn't a known property of 'input'. (" <label for="file">파일</label>
<input type="file" name="single" ng2FileSelect [ERROR ->][uploader]="uploader" >
<button type="button" (click)="uploader.uploadAll()">
"): ng:///BoardModule/BoardCreateComponent.html@22:57
我已经通过jsp完成了上传功能,但是它的方式更加复杂。
您有没有启用上传功能的想法?
我想创建一个标题,作者,文件3个输入的帖子
我也上传了我的代码github。
这是github中的完整代码。
https://github.com/9aram/code-test
board-create.component.ts
import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { BoardService } from '../../services/board.service';
import { Board } from '../../models/Board';
import {FileUploader} from 'ng2-file-upload';
@Component({
selector: 'app-board-create',
templateUrl: './board-create.component.html',
styles: []
})
export class BoardCreateComponent {
//파일 업로드 요청url
uploader:FileUploader = new FileUploader({
url:'http://localhost:3000/board-create'
});
fileInfo = {
originalname:'',
filename:''
};
board: any = {};
constructor(private router: Router, private boardService: BoardService) {
//업로드 요청 결과 받아오는 메소드
this.uploader.onCompleteItem = (item, response, status, header) =>{
this.fileInfo=JSON.parse(response);
};
}
saveBoard(boardForm) {
boardForm.form.value.originalname= this.fileInfo.originalname;
boardForm.for.value.filename=this.fileInfo.filename;
this.boardService.insertBoard(this.board)
.subscribe((res: Board) => { this.router.navigate(['/boards']); }, (err) => console.log(err));
}
}
board-create.component.html
<form #boardForm="ngForm" (ngSubmit)="saveBoard(boardForm)">
<div class="field">
<div class="control">
<label for="title">Title</label>
<input required name="title" id="title" [(ngModel)]="board.title" type="text" class="input">
</div>
</div>
<div class="field">
<div class="control">
<label for="author">Author</label>
<input required name="author" id="author" [(ngModel)]="board.author" type="text" class="input">
</div>
</div>
<div class="field">
<div class="control">
<label for="file">파일</label>
<input type="file" name="single" ng2FileSelect [uploader]="uploader" >
<button type="button" (click)="uploader.uploadAll()">
<<span>uploadd..</span>
</button>
</div>
</div>
<div class="field">
<div class="control">
<button class="button is-warning" routerLink="/boards"><i class="fas fa-arrow-left"></i>Back</button>
<button class="button is-link" type="submit" [disabled]="!boardForm.valid">Create</button>
</div>
</div>
</form>
节点> api.js
const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const Board = require('../models/Board.js');
const bodyParser = require('body-parser');
const cors = require('cors');
const upload=require('../util/upload');
// API ROOT ROUTE
router.get('/', (req, res) => {
res.status(200).json({ status: 200, result: 'success' });
});
router.post('/', (req, res) => {
let newBoard = new Board({
title : request.body.title
}),
newBoard.save();
response.type("application/json");
response.send({
result:true
});
});
// GET ALL BoardS
router.get('/board', (req, res, next) => {
Board.find((err, products) => (err) ? next(err) : res.json(products));
});
// GET A Board
router.get('/board/:id', (req, res, next) => {
Board.findById(req.params.id, (err, post) => (err) ? next(err) : res.json(post));
});
// SAVE A Board
router.post('/board', upload.single('file'), (req, res, next) => {
response.type("application/json");
response.send({result:true,
originalname: request.file.originalname,
filename: request.file.filename()});
Board.create(req.body, (err, post) => (err) ? next(err) : res.json(post));
});
module.exports = router;
upload.js
const multer = require('multer');
const storage = multer.diskStorage({
description:function(request, file, cb){
cb(null, __dirname + '/../upload');
}
filename: function(request, file, cb){
let datetimestamp=Date.now();
let originalFileName=file.originalname;
originalFileName=originalFileName.split('.');
let originalName=originalFileName[originalFileName.length - 1];
cb(null, file.filename + '-' + datetimestamp+ '.'+originalName);
}
});
//starage 객체만들어 multer의 멤버 설정
const upload = multer({
storage: storage
})
//외부에서 upload객체 사용할 수 있또록 함
module.exports = upload;
答案 0 :(得分:1)
请检查下面的代码,以尝试实现相同的功能。
ust call uploadFile(url, file).subscribe() to trigger an upload
import { Injectable } from '@angular/core';
import {HttpClient, HttpParams, HttpRequest, HttpEvent} from '@angular/common/http';
import {Observable} from "rxjs";
@Injectable()
export class UploadService {
constructor(private http: HttpClient) { }
// file from event.target.files[0]
uploadFile(url: string, file: File): Observable<HttpEvent<any>> {
let formData = new FormData();
formData.append('upload', file);
let params = new HttpParams();
const options = {
params: params,
reportProgress: true,
};
const req = new HttpRequest('POST', url, formData, options);
return this.http.request(req);
}
}
您可以通过以下链接获取更多信息。
https://appdividend.com/2018/05/25/angular-6-file-upload-tutorial/