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>

后端代码与前面一样。

相关推荐
indexsunny1 小时前
互联网大厂Java求职面试实战:Spring Boot微服务与Redis缓存场景解析
java·spring boot·redis·缓存·微服务·消息队列·电商
28岁青春痘老男孩6 小时前
JDK8+SpringBoot2.x 升级 JDK 17 + Spring Boot 3.x
java·spring boot
天若有情6737 小时前
校园二手交易系统实战开发全记录(vue+SpringBoot+MySQL)
vue.js·spring boot·mysql
while(1){yan}7 小时前
MyBatis Generator
数据库·spring boot·java-ee·mybatis
奋进的芋圆7 小时前
DataSyncManager 详解与 Spring Boot 迁移指南
java·spring boot·后端
计算机程序设计小李同学7 小时前
个人数据管理系统
java·vue.js·spring boot·后端·web安全
小刘爱搬砖8 小时前
SpringBoot3 + GraalVM安装和初次打包
spring boot·graalvm
_UMR_9 小时前
springboot集成Jasypt实现配置文件启动时自动解密-ENC
java·spring boot·后端
蓝色王者10 小时前
springboot 2.6.13 整合flowable6.8.1
java·spring boot·后端
hashiqimiya12 小时前
springboot事务触发滚动与不滚蛋
java·spring boot·后端