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.files0;

}

}

}

</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>

后端代码与前面一样。

相关推荐
钱栈up1 小时前
VSCode 调试多模块 Maven + Spring Boot 后端:从启动失败到一次跑通
java·spring boot·maven
2601_962189602 小时前
【SpringBoot】使用IDEA创建SpringBoot项目
java·spring boot·intellij-idea
步行cgn2 小时前
Spring Boot 启动报错:MissingServletWebServerFactoryBean 的排查与解决
java·spring boot·后端
步行cgn3 小时前
Spring Boot 项目打包部署详解
java·spring boot·后端
vipxieliang3 小时前
收货地址验证完整方案:省市区与详细地址
java·spring boot
2601_962071004 小时前
【Java EE】SpringBoot的创建与简单使用
spring boot·后端·java-ee
摇滚侠4 小时前
《SpringBoot 3:入门与应用实战》第 9 章 使用 WebMvc 开发进阶 阅读笔记 24
spring boot·笔记·后端
摇滚侠4 小时前
《SpringBoot 3:入门与应用实战》第 9 章 使用 WebMvc 开发应用 阅读笔记 22
javascript·spring boot·笔记
学长毕业设计5 小时前
基于SpringBoot的社区鲜奶订购系统的设计与实现(源码+文档+讲解视频)
java·spring boot·后端
2601_962174175 小时前
小试牛刀-SpringBoot集成SOL链
数据库·spring boot·后端