axios 实现 文件上传

前端代码

  <input type="file" ref="upload" >

 upload(){
        var objfile = this.$refs.upload.files[0];
        // if((objfile.size/1024/1024)>0){
        //   this.$message.info("文件不能大于1MB")
        //   return false;
        // }
        // console.log(this.$refs.upload.files[0])
        // if (objfile.type!="image/jpeg" || objfile.type!="image/png"){
        //   this.$message.info("文件只能是jpg或者png格式")
        //   return false;
        // }
        var formData = new FormData();
        formData.append('file',this.$refs.upload.files[0]);
        var flag;
        fileupload(formData).then(res=>{
            if (res.code!=200){
              console.log(res)
              flag = true;
            }else {
              flag = false;
            }
}

先分装axios请求

import axios from 'axios'

export function request(config) {
  // 1.创建axios的实例
  const instance = axios.create({
    baseURL: 'http://localhost:8888',
    //timeout: 10000,
    headers: {
      'Content-Type': "application/json;charset=utf-8",
      'Authorization': window.sessionStorage.getItem("token")
    },
    changeOrigin: true
  })

  // 2.axios的拦截器
  // 2.1.请求拦截的作用
  instance.interceptors.request.use(config => {
    return config
  }, err => {
    // console.log(err);
  })

  // 2.2.响应拦截
  instance.interceptors.response.use(res => {
    return res.data
  }, err => {
    console.log(err);
  })

  // 3.发送真正的网络请求
  return instance(config)
}

//文件上传 
export function fileupload(data) {
  return request({
    url: '路径',
    headers:{"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"},//设置响应投
    method: 'POST',
    data:data
  });
}

//后端接收

@RequestMapping("fileupload")
    @ResponseBody
    public ResultVO<Boolean> fileupload(@RequestParam("file") MultipartFile file){
        ResultVO<Boolean> resultVO;
        AoaUser aoaUser = getToken.getUser(token);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());					//放入Date类型数据
        String datestr=calendar.get(Calendar.YEAR)+"-"+calendar.get(Calendar.MONTH)+"-"+calendar.get(Calendar.DATE);
        if(file.isEmpty()){
            resultVO = new ResultVO<>(ErrorCode.NULL);
            resultVO.setData(false);
            return resultVO;
        }
        String attachmentName = file.getOriginalFilename();
        String attachmentShuffix = attachmentName.substring(attachmentName.lastIndexOf(".")+1);
        String attachmentPath = "D:/"+datestr+"-"+aoaUser.getUserName()+"-"+UUID.randomUUID()+"."+attachmentShuffix;
        String attachmentSize = file.getSize()+"";
        String attachmentType = "image/"+attachmentShuffix;
        String model = "aoa_bursement";
        Date upload_time = new Date();
        String userId = aoaUser.getUserId().toString();
        AoaAttachmentList aoaAttachmentList = new AoaAttachmentList(attachmentName,attachmentPath,attachmentShuffix,attachmentSize,attachmentType,model,upload_time,userId);

        File dest = new File(attachmentPath);
        if(!dest.getParentFile().exists()){ //判断文件父目录是否存在
            dest.getParentFile().mkdir();
        }
        try {
            file.transferTo(dest); //保存文件
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            resultVO = new ResultVO<>(ErrorCode.NULL);
            resultVO.setData(false);
            return resultVO;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            resultVO = new ResultVO<>(ErrorCode.NULL);
            resultVO.setData(false);
            return resultVO;
        }
        aoaAttachmentList = aoaAttachmentListService.insertAtt(aoaAttachmentList);
        Long proFileId = aoaAttachmentList.getAttachmentId();

        if (aoaAttachmentList.getAttachmentId()!=0 ){
            resultVO = new ResultVO<>(ErrorCode.SUCCESS);
            resultVO.setData(true);
            return resultVO;
        }else {
            resultVO = new ResultVO<>(ErrorCode.NULL);
            resultVO.setData(false);
            return resultVO;
        }

    }
  • 6
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值