angular 前后端上传文件

    <form (ngSubmit)="doSubmit()" enctype="multipart/form-data">
            <mat-label>文件</mat-label> &nbsp;

            <input name="file" type="file" (change)="upload($event)">
            &nbsp;&nbsp;&nbsp;
            <input type="submit" aria-label="SAVE" value="确定上传" style="color: blue;">

        </form>

ts部分:

file: any;
  upload(e: any): void {
    this.file = e.target.files[0];
    if (this.file != null) {
      this.msg.success('已经选择文件');
    }
    console.log(this.file);
  //  const formData: FormData = new FormData();

   // formData.append('file', this.file);

  //  this.http.post(environment.frontPath + '/sys/test/outImport', formData).subscribe(res => {
  //    if (res.statusCode == 200) {
    //    this.msg.success('上传成功');
    //  }

   // })
  }

  doSubmit(): void {

    console.log(111);

    const formData: FormData = new FormData();

    formData.append('file', this.file);

    this.http.post(environment.frontPath + '/sys/test/outImport', formData).subscribe(res => {
      if (res.statusCode == 200) {
        this.msg.success('上传成功');
      }

    })
  }

后台java接收文件处理

@RequestMapping(value = "/outImport")
@ResponseBody
public Object outImport(@RequestParam(value = "file") MultipartFile file) {
    try {

        if (file.isEmpty()) {
            System.out.println("文件为空空");
            return NetResponse.ok("文件为空");
        }
        String fileName = file.getOriginalFilename();  // 文件名
        System.out.println(fileName);
        System.out.println(222188888);
        String suffixName = fileName.substring(fileName.lastIndexOf("."));  // 后缀名
        System.out.println(suffixName);
        String filePath = "E://temp-rainy//"; // 上传后的路径
        fileName = UUID.randomUUID() + suffixName; // 新文件名
        File dest = new File(filePath + fileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return NetResponse.ok("操作成功");
    } catch (Exception e) {
        return NetResponse.error(NetResponse.ERROR,"操作失败", e);
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值