generator-ng-fullstack icon indicating copy to clipboard operation
generator-ng-fullstack copied to clipboard

can not upload file in angular 2 when using ng-fullstack

Open ducduongtmb opened this issue 10 years ago • 9 comments

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>

ducduongtmb avatar Jun 17 '16 15:06 ducduongtmb

Hello, @ducduongtmb.

What the code in /api/media?

ericmdantas avatar Jun 17 '16 17:06 ericmdantas

@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 .

ducduongtmb avatar Jun 19 '16 07:06 ducduongtmb

@ericmdantas I think it's problem of server .

ducduongtmb avatar Jun 19 '16 14:06 ducduongtmb

Yeah, sounds like it.

What does the network tab on chrome says? Is the info being transmitted alright?

ericmdantas avatar Jun 19 '16 16:06 ericmdantas

@ericmdantas Sorry for the late reply . I'm living Vietnam . this is console in Chrome

image

this is network tab . Nothing is sent .

image

image

I'm doing my capstone project by your ng-fullstack . I can't slove this problem . thanks you for help .

ducduongtmb avatar Jun 20 '16 04:06 ducduongtmb

@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 ???

ducduongtmb avatar Jun 20 '16 04:06 ducduongtmb

Oh, its the middleware for validation of payload.

Comment this line:

application.use(contentLength.validateMax({max: 999}));

In routes.conf.js.

ericmdantas avatar Jun 20 '16 10:06 ericmdantas

@ericmdantas thanks you so much :dancer:

ducduongtmb avatar Jun 20 '16 14:06 ducduongtmb

:+1:

ericmdantas avatar Jun 20 '16 14:06 ericmdantas