can not upload file in angular 2 when using ng-fullstack
I use this library : https://github.com/valor-software/ng2-file-upload
but application console log bad request 400 .
and then I follow this tutorial
https://www.thepolyglotdeveloper.com/2016/02/upload-files-to-node-js-using-angular-2/
and It still console log bad request 400 .
Why ? I can't use xhr to upload file ? or I can't use ng2-file-upload to upload file to server .
This is my code now .
media.ts
import {
Component,
Inject,
OnInit,
ElementRef
} from '@angular/core';
import { Http, Response,HTTP_PROVIDERS, Headers,RequestOptions } from '@angular/http';
import { FormBuilder, ControlGroup, Control } from '@angular/common';
import { AuthService } from '../dashboard/services/auth-services';
import {CORE_DIRECTIVES, FORM_DIRECTIVES, NgClass, NgStyle} from '@angular/common';
import {FILE_UPLOAD_DIRECTIVES, FileUploader} from 'ng2-file-upload';
import { Media } from '../dashboard/interface/media';
import {MediaService} from "../dashboard/services/media-service";
import {Observable} from 'rxjs/Rx';
const URL = '/api/media';
@Component({
selector: 'demo',
templateUrl: 'client/dev/demo/demo.html',// indicate html page
directives: [FILE_UPLOAD_DIRECTIVES, NgClass, NgStyle, CORE_DIRECTIVES, FORM_DIRECTIVES],
providers:[
HTTP_PROVIDERS,
AuthService,
MediaService]
})
export class DemoComponent implements OnInit{
user:string;
pathLocal:string="";
filesWUpload:File;
uploader:FileUploader = new FileUploader({url: URL});
filesToUpload: Array<File>;
constructor(private _elRef:ElementRef,private _authService: AuthService,private mediaService:MediaService ,private _http: Http ){
this.filesToUpload = [];
}
upload() {
this.makeFileRequest("/api/media", [], this.filesToUpload).then((result) => {
console.log(result);
}, (error) => {
console.log(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);
}
}
}
var cd = "form-data,name='imageUpload'";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Disposition", cd);
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
});
}
ngOnInit() {
}
}
media.html
<input type="file" name="imageUpload" (change)="fileChangeEvent($event)" placeholder="Upload file..." />
<button type="button" (click)="upload()">Upload</button>
Hello, @ducduongtmb.
What the code in /api/media?
@ericmdantas This is my code in server
routes.conf.js
"use strict";
const morgan = require('morgan');
const bodyParser = require('body-parser');
const contentLength = require('express-content-length-validator');
const helmet = require('helmet');
const express = require('express');
const passport = require('passport');
const expressSession = require('express-session');
module.exports = class RouteConfig {
static init(application) {
let _root = process.cwd();
let _clientFiles = (process.env.NODE_ENV === 'production') ? '/client/dist/' : '/client/dev/';
application.use(express.static(_root));
application.use(express.static(_root + _clientFiles));
application.use(bodyParser.json());
// parse application/x-www-form-urlencoded
application.use(bodyParser.urlencoded({extended: true}));
application.use(morgan('dev'));
application.use(contentLength.validateMax({max: 999}));
application.use(helmet());
require('../api/user/config/passport')(passport);
application.use(expressSession({
secret: 'kshare',
cookie: {maxAge: 60000},
secure: false,
httpOnly: false,
resave: true,
saveUninitialized: true
}));
// Add passport's middleware
application.use(passport.initialize());
application.use(passport.session());
}
}
media-controller.js
"use strict";
module.exports = class mediaController {
static createMedia(req,res){
console.log("hello");
}
}
media-router.js
"use strict";
const mediaController = require('../controller/media-controller');
module.exports = class mediaRoutes {
static init(router) {
router
.route('/api/media')
.post(mediaController.createMedia);
}
}
routes\index.js
"use strict";
const mediaRoutes = require('../api/media/router/media-router');
module.exports = class Routes {
static init(app, router) {
mediaRoutes.init(router);
router
.route('*')
.get(StaticDispatcher.sendIndex);
app.use('/', router);
}
}
I just want to console.log("Hello") to know that client can send data to server . But It can't .
@ericmdantas I think it's problem of server .
Yeah, sounds like it.
What does the network tab on chrome says? Is the info being transmitted alright?
@ericmdantas Sorry for the late reply . I'm living Vietnam . this is console in Chrome

this is network tab . Nothing is sent .


I'm doing my capstone project by your ng-fullstack . I can't slove this problem . thanks you for help .
@ericmdantas I can go to server with postman . when I use Postman and send something to server , server can console "hello" . It mean that my client has error ???
Oh, its the middleware for validation of payload.
Comment this line:
application.use(contentLength.validateMax({max: 999}));
In routes.conf.js.
@ericmdantas thanks you so much :dancer:
:+1: