angular ng2-file-upload 上传多视频、多图片,并本地预览;后端C#接收

做好的效果展示:

在这里插入图片描述

1、 安装ng2-file-upload

npm install ng2-file-upload --save

2、集成到module中

在appmodule中:

import { FileUploadModule } from 'ng2-file-upload';

@NgModule({
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    FileUploadModule,  //注意引入
  ]
})

3、因为参考靠其他博客只能上传一个视频或图片,不能多个上传,所以继承了FileUploader,代码如下:

  • 新建mutipleupload.ts
import { FileUploader, FileItem, FileUploaderOptions } from 'ng2-file-upload';

export class MutipleuploadService extends FileUploader{

  constructor(options: FileUploaderOptions) {
    super(options);
  }

  uploadAllFiles(): XMLHttpRequest {

    var xhr = new XMLHttpRequest();
    var sendable = new FormData();
    var fakeitem: FileItem = null;
    this.onBuildItemForm(fakeitem, sendable);

    for (const item of this.queue) {
      item.isReady = true;
      item.isUploading = true;
      item.isUploaded = false;
      item.isSuccess = false;
      item.isCancel = false;
      item.isError = false;
      item.progress = 0;

      if (typeof item._file.size !== 'number') {
        throw new TypeError('The file specified is no longer valid');
      }
      sendable.append("files", item._file, item.file.name);
    }

    this.queue=[];

    if (this.options.additionalParameter !== undefined) {
      Object.keys(this.options.additionalParameter).forEach((key) => {
        sendable.append(key, this.options.additionalParameter[key]);
      });
    }

    xhr.onload = () => {
      var gist = (xhr.status >= 200 && xhr.status < 300) || xhr.status === 304 ? 'Success' : 'Error';
      var method = 'on' + gist + 'Item';
      this[method](fakeitem, null, xhr.status, null);
    };

    xhr.onerror = () => {
      this.onErrorItem(fakeitem, null, xhr.status, null);
    };

    xhr.onabort = () => {
      this.onErrorItem(fakeitem, null, xhr.status, null);
    };

    xhr.open("POST", this.options.url, true);
    
    xhr.withCredentials = false;

    if (this.options.headers) {
      for (var _i = 0, _a = this.options.headers; _i < _a.length; _i++) {
        var header = _a[_i];
        xhr.setRequestHeader(header.name, header.value);
      }
    }

    if (this.authToken) {
      xhr.setRequestHeader(this.authTokenHeader, this.authToken);
    }
    xhr.send(sendable);

    return xhr;
  };

}

  • 在用到的component中引入该类
import { MutipleuploadService } from '../../utils/mutipleupload.service';

@Component({
  selector: 'app-visitedreport',
  templateUrl: './visitedreport.component.html',
  styleUrls: ['./visitedreport.component.css']
})
export class VisitedreportComponent implements OnInit {

  public uploader: MutipleuploadService = new MutipleuploadService({
    url: this.postFileURL,
    method: "POST",
    itemAlias: "uploadedfile",
  });

  //上传图片
  uploadPicture() {
    this.uploader.onBuildItemForm = (fileItem: any, form: any) => {
      form.append('visitingdemandid', this.visitingdemandid);
      form.append('type', "PICTURE");
    };
    var that=this;
    this.uploader.uploadAllFiles().onreadystatechange = function () {
      if(this.readyState==4){
        if(this.status==200){
          that.pciturePaths=JSON.parse(this.response).response;
          console.log(JSON.parse(this.response).response);
        }
      }
    }
  }

  //上传视频
  uploadVideo(){
    this.uploader.onBuildItemForm = (fileItem: any, form: any) => {
      form.append('visitingdemandid', this.visitingdemandid);
      form.append('type', "VIDEO");
    };
    var that=this;
    this.uploader.uploadAllFiles().onreadystatechange = function () {
      if(this.readyState==4){
        if(this.status==200){
          that.videoPaths=JSON.parse(this.response).response;
          console.log(JSON.parse(this.response).response);
        }
      }
    }
  }
}

html模板:

<div class="weui_cell">
          <div class="weui_cell_bd weui_cell_primary">
            <div class="weui_uploader">
              <div class="weui_uploader_hd weui_cell">
                <div class="weui_cell_bd weui_cell_primary">图片上传</div>
              </div>
              <div class="weui_uploader_bd">
                <ul class="weui_uploader_files"> 
                  <li class="weui_uploader_file" *ngFor="let path of pciturePaths"  [ngStyle]="{'background-image':'url(http://localhost:55077'+path+')'}"></li>
                </ul>
                <div class="weui_uploader_input_wrp">
                  <input class="weui_uploader_input" type="file" accept="image/jpg,image/jpeg,image/png,image/gif,video/*" ng2FileSelect [uploader]="uploader" (change)="uploadPicture()" multiple/>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="weui_cell">
          <div class="weui_cell_bd weui_cell_primary">
            <div class="weui_uploader">
              <div class="weui_uploader_hd weui_cell">
                <div class="weui_cell_bd weui_cell_primary">视频上传</div>
              </div>
              <div class="weui_uploader_bd">
                <div>
                    <video controls="controls" width="100%"  height="200"  *ngFor="let path of videoPaths" src="http://localhost:55077/{{path}}">Your browser can't support HTML5 Audio</video>
                </div>
                <div class="weui_uploader_input_wrp">
                  <input class="weui_uploader_input" type="file" accept="video/*" ng2FileSelect [uploader]="uploader" (change)="uploadVideo()" multiple/>
                </div>
              </div>
            </div>
          </div>
        </div>

注意:如果前后端分离,会遇到跨域问题,上传文件浏览器拦截通配符之类的问题:xhr.withCredentials = false;(不验证通配符)。如果上传视频,记得后端设置最大上传长度。

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值