加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Angular 2 / Express将文件上传到服务器

发布时间:2020-12-17 17:00:41 所属栏目:安全 来源:网络整理
导读:我是Angular2和Express的新手,我无法将文件上传到服务器.我已经在JS,PHP和HTML中创建了一个基本的文件上传器,但似乎无法使用Angular2和Express.任何帮助,将不胜感激.我正在寻找文件/图像上传到服务器的答案. :).如果我走向错误的方向,那么构建一个新的简单项
我是Angular2和Express的新手,我无法将文件上传到服务器.我已经在JS,PHP和HTML中创建了一个基本的文件上传器,但似乎无法使用Angular2和Express.任何帮助,将不胜感激.我正在寻找文件/图像上传到服务器的答案. :).如果我走向错误的方向,那么构建一个新的简单项目会更容易.

目前我正试图在angular-cli项目中复制它:

https://github.com/coligo-io/file-uploader

问题:
我想我一直在发送邮件请求发送快递,请参阅下面的代码.当我测试这个时,我运行构建,然后运行node server.js.我可以选择一个文件,但在我选择文件后,当它应该上传到’uploads’目录中的服务器时没有任何反应.

App.Component.ts

import { Component,ElementRef,ViewChild,Injectable } from '@angular/core';
import { Http } from '@angular/http';

@Component({
  selector: 'app-root',templateUrl: './app.component.html',styleUrls: ['./app.component.css']
})

@Injectable()
export class AppComponent {
  title = 'app works!';

  @ViewChild('upload-btn') uploadbtn;
  @ViewChild('inputFile') inputFile:ElementRef;
  @ViewChild('progressBar') progressBar;

  constructor(private http: Http,private e1: ElementRef){}

  /* When button is clicked open input */
  upload(){
    console.log("clicked");
    this.inputFile.nativeElement.click();
  } // end of upload

  /* Process input form */
  sendToServer(){
      // Get form input
      let inputFile: HTMLInputElement = this.inputFile.nativeElement;

      let fileCount: number = inputFile.files.length;

      let formData = new FormData();

      console.log("File Count: " + fileCount);

      if( fileCount > 0 ){
        for(let i = 0; i < fileCount; i++){
          console.log("Count: " + i);
          formData.append('uploads[]',inputFile.files.item(i),inputFile.files.item(i).name);
        }
        console.log("Form Data: " + formData);

        this.http.post('http:/localhost:3000/upload',formData);
        console.log("file uploaded");
      }

  } // end of send to server

}

App.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],imports: [
    BrowserModule,FormsModule,HttpModule
  ],providers: [],bootstrap: [AppComponent]
})
export class AppModule { }

App.component.html

<div class="container">
  <div class="row">
    <div class="col-xs-12">
      <div class="panel panel-default">
        <div class="panel-body">
          <span class="glyphicon glyphicon-cloud-upload"></span>
          <h2>File Uploader</h2>
          <h4>coligo.io</h4>
          <div class="progress">
            <div #progressBar class="progress-bar" role="progressbar"></div>
          </div>
          <button (click)="upload()" class="btn btn-lg upload-btn" type="button">Upload File</button>
        </div>
      </div>
    </div>
  </div>
</div>

<input #inputFile  (change)="sendToServer()" id="upload-input" type="file" name="uploads[]" multiple="multiple"><br/>

Server.js

var express = require('express');
var app = express();
var path = require('path');
var formidable = require('formidable');
var fs = require('fs');

app.use(express.static(path.join(__dirname,'dist')));

app.get('/',function(req,res){
  res.sendFile(path.join(__dirname,'dist/index.html'));
});

app.post('/upload',res){
  console.log("Server Hit");
  // create an incoming form object
  var form = new formidable.IncomingForm();

  // specify that we want to allow the user to upload multiple files in a single request
  form.multiples = true;

  // store all uploads in the /uploads directory
  form.uploadDir = path.join(__dirname,'/uploads');

  // every time a file has been uploaded successfully,// rename it to it's orignal name
  form.on('file',function(field,file) {
    fs.rename(file.path,path.join(form.uploadDir,file.name));
  });

  // log any errors that occur
  form.on('error',function(err) {
    console.log('An error has occured: n' + err);
  });

  // once all the files have been uploaded,send a response to the client
  form.on('end',function() {
    res.end('success');
  });

  // parse the incoming request containing the form data
  form.parse(req);

});

var server = app.listen(3000,function(){
  console.log('Server listening on port 3000');
});

File Structure for attempt 2

谢谢您的帮助.对此,我真的非常感激.

解决方法

您需要以角度订阅请求

例如

this.http.post('http:/localhost:3000/upload',formData)
    .subscribe();

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读