ionic4结合ng2-file-upload实现手机端图片上传

上传图片折腾了好几天,终于实现了,记录一下。

1、安装插件 ng2-file-upload ,cnpm install ng2-file-upload --save
在这里插入图片描述

2、在需要使用插件的页面的module.ts文件中加入依赖
在这里插入图片描述
注意:如果这一步不加入依赖,会出现下面的错误
在这里插入图片描述

3、在相应的ts文件中加入依赖,并声明FileUploader类型的变量

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

// 声明一个FileUploader类型的变量,并将其初始化
    public uploader: FileUploader = new FileUploader({
      url: this.uploadPictureUrl,
      method: 'POST',
      // autoUpload: true,
      removeAfterUpload: true,
      itemAlias: 'multfile'
      // allowedFileType: ['image']
    });

4、html

<div class="item act-cell-padding" style="height: 160px;">         
            <span>活动文案:</span>
            <div class="picPlace">
              <img id="wizardPicturePreview" name="picture" src="{{picture}}" style="height:100px;  width:100px;display:block; border:1px solid #CCC" alt="" class="picture-src" title="" />
              <input #file type="file" id="file" class="showPicture"  ng2FileSelect  [uploader]="uploader" (change)="selectedFileOnChanged(file)">
            </div>       
        </div>

5、ts文件中加入change事件,上传图片到fastdfs,然后接受fastdfs返回的图片地址

// 选择上传图片
public selectedFileOnChanged(file: HTMLInputElement) {
  let length: number;
  this.editPicture = !this.editPicture;
  this.fileName = file.value;
  const fileDot: string = this.fileName.substring(this.fileName.lastIndexOf('.') + 1, this.fileName.length);

   // 开始上传
   this.uploader.queue[0].upload();

    this.uploader.queue[0].onSuccess = function(response, status, headers) {
    // 上传文件成功
    if (status === 200) {
      // 上传文件后获取服务器返回的数据
      const temRes = JSON.parse(response);
      let data = temRes.data;
      // 修改页面图片
      const el: Element = document.getElementById('wizardPicturePreview');
      el.setAttribute('src', data);

      length = data.length;
      data = data.substring(21, length);
      this.picture = data;
      localStorage.setItem('picUrl', 'http://192.168.22.64/' + data);
    } else {
      alert('上传图片失败');
    }
  };
}

6、后端实现图片上传

/**
     * saveImage-保存图片
     *
     * @Params: file 文件
     * @author 
     * @since 0.0.1 2018-8-6 14:43:57
     */
    @ApiOperation(value = "上传图片")
    @PostMapping(value = {"/upload"})
    public IntegralResult<String> uploadImage(@RequestParam(value="multfile",required=false)MultipartFile file) {

        try {
            String imagePath = medalService.saveImage(file);
            return IntegralResult.build(IntegralResult.SUCCESS, "文件:" + file.getName() + "上传成功", imagePath);
        } catch (IOException e) {
            return IntegralResult.build(IntegralResult.FAIL, "上传失败", e.getMessage());
        }
    }

注意:@RequestParam(value=“multfile”)需要和new FileUploader中的别名itemAlias: 'multfile’一致,否者后端接收到的file始终都是null

7、需要配置全部cose跨域

private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        corsConfiguration.setAllowCredentials(true);
        return corsConfiguration;
    }

参考链接:SpringBoot配置Cors解决跨域请求问题

注意:初始使用这个方法的时候,没有“ corsConfiguration.setAllowCredentials(true);”这句配置,出现以下错误
在这里插入图片描述

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

木子松的猫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值