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>

后端代码与前面一样。

相关推荐
今年下半年7 小时前
【VUE3】移动端:使用腾讯地图显示区域统计与放大显示资产点位
javascript·前端框架·vue·地图
卓怡学长7 小时前
w202springboot基于B_S架构的图书信息管理系统
java·spring boot·spring·intellij-idea
走到天涯海角8 小时前
用springBoot写几个简单的接口
java·spring boot·intellij-idea
xcl09258 小时前
西安同城货运系统源码开发实战 核心功能实现与部署全指南
java·spring boot
志尊宝9 小时前
Vue3 零基础每日笔记(054):Pinia 三件套详解——state / getters / actions 全搞懂
前端·javascript·vue.js·vue·前端开发
ym hyd 1119 小时前
慢性病精细化管理平台源码 Java+SpringBoot+Vue3 前后分离
java·vue.js·spring boot·毕设
RuoyiOffice9 小时前
SpringBoot3+Vue3 低代码业务表单:从拖拽设计、独立建表到审批与数据查询
spring boot·vue3·数据建模·flowable·版本管理·低代码表单·ruoyi office
需要8269 小时前
MySQL MVCC 与事务隔离级别:从一条 update 看版本链
java·数据库·spring boot·mysql·spring cloud
RuoyiOffice9 小时前
SpringBoot3 企业薪酬核算:考勤、绩效与薪资规则如何算出一张可解释的工资单
spring boot·vue3·规则引擎·hrm·ruoyi office·薪酬核算·薪资试算
阿狗童鞋11 小时前
SpringBoot微服务实战指南
spring boot·后端·微服务