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

做好的效果展示:

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

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模板:

图片上传
视频上传

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

你可能感兴趣的:(前端菜鸟)