springboot项目上传文件

单纯只想分享给大家自己的开发经验,不足之处,请大家多多体谅!

1、前端引用组件

"ng2-file-upload": "^1.4.0",

2、前端页面代码

<div class="form-group">
        <label for="file">文件:</label>
        <input type="file" formControlName="filepath"  ng2FileSelect [uploader]="uploader1" (change)="selectedFileOnChanged($event)" nbInput id="file" fieldSize="small">
      </div>

3、ts代码

    // 初始化uploader1
  	uploader1: FileUploader;
	async ngOnInit() {
	    this.token = await this.storage.getLoginUser();
	    console.log(this.token);
	    this.uploader1 = new FileUploader({
	      url: 'http://localhost:8080/file/uploadFile',
	      method: 'POST',
	      itemAlias: 'multipartFile',   //这个是后端的参数名
	      autoUpload: false,
	      // removeAfterUpload: true,
	      // allowedFileType: ['xlsx', 'xls'],
	    });
	  }
	
	  //选择文件时触发的方法
	  selectedFileOnChanged(event: any) {
	    console.log(event);
	    this.selectFileName = event.target.value.substr(event.target.value.lastIndexOf('\\') + 1);
	    this.uploader1.authToken =  'Bearer ' + this.token;
	    console.log(this.selectFileName);
	    this.uploadFile();
	  }
	
	//真正的上传方法
	  async uploadFile() {
	    console.log('uploadFile');
	    console.log(this.token);
	    console.log(this.uploader1);
	    // 上传跨域验证
	    this.uploader1.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 === 200) {
	          const res = JSON.parse(response);
	          console.log('res', res);
	        } else {
	          console.log('err', response, status, headers); // 判断错在哪
	          console.log('err', Error);
	        }
	      };
	      queue.upload();
	    });
	  }
	
	//点击外部弹框保存时触发的方法
	  async uploadFileInfo() {
	    const fileInfo = this.fileUploadForm.getRawValue();
	    console.log(fileInfo);
	    const info = await this.httpService.post(API.uploadFile, fileInfo);
	    if (info) {
	      await this.nativeService.showToast('success', '提示', '操作成功');
	      await this.router.navigateByUrl('/message-management/file-management');
	    }
	  }

3、后端代码

controller

 @RequestMapping("uploadFile")
    public ResponseResult uploadFile(MultipartFile multipartFile) throws Exception {
        return ResponseResult.success(fileUploadUtil.upload(multipartFile));
    }

FileUploadUtil

@Slf4j
@Component
public class FileUploadUtil {
    private static final String filePath = "FilePath";

    @Resource
    private SysParamsMapper sysParamsMapper;

    /**
     * 上传文件并返回存储路径
     *
     * @param multipartFile
     * @return
     */
    public String upload(MultipartFile multipartFile) throws Exception {
        log.info("上传文件开始...");
        String path = "";
        if (!multipartFile.isEmpty()) {
            SysParamsExample sysParamsExample = new SysParamsExample();
            sysParamsExample.createCriteria().andInnerNameEqualTo(filePath);
//            String storePath = sysParamsMapper.selectByExample(sysParamsExample).get(0).getValue();
            String storePath="D:/";
            String uploadFileName = multipartFile.getOriginalFilename();
            log.info("文件名称: " + uploadFileName);
            String fileName = UUID.randomUUID() + "_" + uploadFileName;
            path = storePath + "/" + fileName;
            log.info("文件路径: " + path);
            File tmpFile = new File(path);
            if (!tmpFile.exists()) {
                tmpFile.mkdirs();
            }
            multipartFile.transferTo(tmpFile);
        } else {
            log.error("文件为空");
            throw new I2WorkException(Constant.ResponseCode.ERROR, "上传文件为空!");
        }
        log.info("上传文件结束");
        return path;
    }
}

结束语:一辈子很短,努力的做好两件事就好;第一件事是热爱生活,好好的去爱身边的人;第二件事是努力学习,在工作中取得不一样的成绩,实现自己的价值,而不是仅仅为了赚钱,加油!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值