Я сделал среднюю стопку сырой доски, и она хорошо работает. (angular2 +, node.js, экспресс, 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
доска-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));
}
}
доска-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;