angualr4上传图片(文件)

借鉴地址:https://valor-software.com/ng2-file-upload/

心得:
1.http状态码:
200:成功 服务器已成功处理了请求。如果是对您的 robots.txt 文件显示此状态码,则表示 Googlebot 已成功检索到该文件。
201 创建 表示服务器执行成功,并且创建了新的资源
202 已接受 服务器接受请求,但未处理
203 非授权信息 服务器成功执行了请求,但是返回的信息可能来自另一来源
204 空内容 服务器成功执行请求,但是没有返回信息
205 重置内容 服务器成功执行了请求,但是但是没有返回内容,与204不同,他需要请求者重置文档视图(比如,清除表单内容,重新输入)
206 部分内容 服务器成功执行了部分请求

2.判断错在哪里同样重要

//console.log("err",response, status, headers);//判断错在哪同样重要

主要部分笔记:
A:install

npm install ng2-file-upload --save

B.html

<input type="file"  ng2FileSelect [uploader]="uploader" (change)="selectedFileOnChanged($event)" />

C:引入

//ts
import {FileUploader } from 'ng2-file-upload/ng2-file-upload';

//模块module.ts
import { FileUploadModule } from 'ng2-file-upload';
并在import中声明:FileUploadModule

D:定义初始化:

 public hasBaseDropZoneOver:boolean = false;
    public hasAnotherDropZoneOver:boolean = false;

    public fileOverBase(e:any):void {
        this.hasBaseDropZoneOver = e;
    }

    public fileOverAnother(e:any):void {
        this.hasAnotherDropZoneOver = e;
    }
    //初始化
    uploader:FileUploader = new FileUploader({
        url: "http://editor-sms.wei7star.com/codeeditor/file/",
        removeAfterUpload: true,
    });

E:定义事件,上传文件:

   // C: 定义事件,选择文件
    selectedFileOnChanged(event:any) {
        //console.log(event.target.value);
        this.upload();
    }

    upload() {
        //上传跨域验证
        this.uploader.queue.forEach(queue => {
            queue.withCredentials = false;
            queue.onError = (response: string, status: number, headers: ParsedResponseHeaders) => {
                console.log(response, status, headers);
            };

            queue.onSuccess = (response, status, headers) => {
                if (status == 201) {
                    let res = JSON.parse(response);
                    console.log("res", res);
                } else {
                    //console.log("err",response, status, headers);//判断错在哪同样重要
                    console.log("err",Error);
                }
            };

            queue.upload();
        });
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值