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>

后端代码与前面一样。

相关推荐
不吃香菜学java2 小时前
Redis的java客户端
java·开发语言·spring boot·redis·缓存
橙露3 小时前
SpringBoot 整合 MinIO:分布式文件存储上传下载
spring boot·分布式·后端
小眼哥4 小时前
SpringBoot整合Vue代码生成exe运行程序以及windows安装包
vue.js·windows·spring boot
阿部多瑞 ABU4 小时前
《智能学号抽取系统》V5.9.5 发布:精简代码,修复移动端文件读取核心 Bug
vue·html·bug
shark22222227 小时前
能懂!基于Springboot的用户增删查改(三层设计模式)
spring boot·后端·设计模式
IGAn CTOU8 小时前
王炸级更新!Spring Boot 3.4 正式发布,新特性真香!
java·spring boot·后端
indexsunny10 小时前
互联网大厂Java面试实战:核心技术与微服务架构在电商场景中的应用
java·spring boot·redis·kafka·maven·spring security·microservices
海兰10 小时前
【第3篇-续】多模型多模态项目实现示例(增加OpenAI通用适配)附源代码
java·人工智能·spring boot·alibaba·spring ai
SarL EMEN11 小时前
海康威视摄像头ISUP(原EHOME协议) 摄像头实时预览springboot 版本java实现,并可以在浏览器vue前端播放(附带源码)
java·前端·spring boot
ccice0111 小时前
全面掌握Spring Boot + MyBatis + Maven + MySQL:从开发到部署的后端技术详解
spring boot·maven·mybatis