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>

后端代码与前面一样。

相关推荐
Spider Cat 蜘蛛猫6 小时前
Springboot SSO系统设计文档
java·spring boot·后端
学习3人组16 小时前
业务主表+JSON自定义字段
java·spring boot·json
吕永强17 小时前
基于SpringBoot+Vue宠物领养系统的设计与实现(源码+论文+部署)
spring boot·毕业设计·毕业论文·宠物领养·宠物领养系统
yoyo_zzm17 小时前
PHP vs Java:后端语言终极选择指南
java·spring boot·后端·架构·php
鱼鳞_18 小时前
苍穹外卖-Day01(开发环境搭建)
java·spring boot·spring·maven
学不思则罔18 小时前
SpringBoot启动失败排查指南
spring boot·后端·部署
夕除18 小时前
spring boot 5
数据库·spring boot·后端
yoyo_zzm19 小时前
ThinkPHP1.X核心特性解析
数据库·spring boot·nginx
hexu_blog19 小时前
前端vue后端java+springboot如何实现pdf,word,excel之间的相互转换
java·前端·vue.js·spring boot·文档转换
倒流时光三十年20 小时前
第9篇 消息不丢:三端协同防丢失方案
spring boot·kafka