axios+springboot上传图片到本地(vue)

结果:

前端文件:

<template>

   <div>

    <input type="file" id="file" ref="file" v-on:change="handleFileUpload()"/>

    <button @click="submitFile">上传</button>

  </div>

</template>

<script>

 import axios from 'axios';

 export default {

   

    data(){

      return {

        file: ''

      }

    },

    methods: {

      submitFile(){

            let formData = new FormData();

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

            axios.post( 'http://localhost:8080/upload/photos',

                formData,

                {

                headers: {

                    'Content-Type': 'multipart/form-data'

                }

              }

            ).then(function(){

          console.log('SUCCESS!!');

        })

        .catch(function(){

          console.log('FAILURE!!');

        });

      },

      handleFileUpload(){

        this.file = this.$refs.file.files[0];

      }

    }

  }

</script>

<style scoped>

  .btn_pos{

      margin-top: 0px;

  }

</style>

后端代码:

@CrossOrigin
@RestController
@RequestMapping("/upload")
public class ImageController {
private final String UPLOAD_PATH = "D:/Download/";//写上你需要上传的本地路径(模拟服务器)

@PostMapping("/photos")
public ResponseEntity<String> uploadFile(@RequestParam MultipartFile file) {
    // ... File upload logic ...
    if (file.isEmpty()) {
        System.out.println("文件为空");
        return new ResponseEntity<>("文件不能为空", HttpStatus.BAD_REQUEST);
    }
    try {
        byte[] bytes = file.getBytes();
        Path path = Paths.get(UPLOAD_PATH + File.separator + file.getOriginalFilename());
        System.out.println("path: " + path);
        Files.write(path, bytes);
        return new ResponseEntity<>("文件上传成功", HttpStatus.OK);
    } catch (IOException e) {
        e.printStackTrace();
        return new ResponseEntity<>("文件上传失败", HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

另一种方式:HTTP请求 

使用elementplus组件<el-upload>:

<template>

  <div>

    <el-upload

      drag

      action="http://localhost:8080/upload/photos"

      :on-success="handleUploadSuccess"

      :on-error="handleUploadError"

    >

      <i class="el-icon-upload"></i>

      <div class="el-upload__text">拖拽文件到此处上传</div>

    </el-upload>

  </div>

</template>

<script>

export default {

methods: {

  handleUploadSuccess(response, file) {

    this.$message.success('文件上传成功');

  },

  handleUploadError(err, file) {

    this.$message.error('文件上传失败');

  }

}

};

</script>

后端代码与前面一样。

  • 23
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值