文章自用,仅作参考
本文章记录基于axios POST请求发送图片到后端
以及使用Spring Boot接收保存图片,在返回文件保存的URL地址
1.前端(Vue + axios)
<template>
<div>
<input type="file" name="" id="fileload" @change="handleChange">
<img src="" alt="图片未加载">
</div>
</template>
<script>
import axios from 'axios'
export default {
methods: {
handleChange (e) {
console.log(e.target.files[0])
const fd = new FormData()
fd.append('img', e.target.files[0])
axios({
url: 'http://localhost:8081',
method: 'post',
data: fd
}).then(res => {
console.log(res)
})
}
}
}
</script>
<style>
</style>
页面效果
代码分析:
@change当文件选择框发生改变时,调用handleChange方法获取图片二进制数据并通过axios发送
2.后端(java + Spring Boot)
控制层(接收并保存文件)
package xyz.ascion_hub.imglload;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
/**
* Describe the feature.
*
* @author AScion
* date 2024/8/14
*/
@RestController
public class Request {
@PostMapping("/")
public String uploadFile(@RequestParam("img") MultipartFile file) throws IOException {
OutputStream os = new FileOutputStream(new File("src/main/resources/static/imgs/1.jpg"));
os.write(file.getBytes());
os.flush();
os.close();
return "http://localhost:8081/imgs/1.jpg";
}
}
代码分析
@RequestParam(“img”) MultipartFile file 获取文件
余下四行使用二进制输出流保存文件
http配置类(配置静态资源位置)
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* Describe the feature.
*
* @author AScion
* creat date: 2024/8/14
*/
@Configuration
public class HTTPConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
WebMvcConfigurer.super.addCorsMappings(registry);
registry.addMapping("/**")
.allowedOrigins("*")
.allowedHeaders("*")
.allowedMethods("POST", "GET", "PUT", "DELETE", "OPTIONS");
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
WebMvcConfigurer.super.addResourceHandlers(registry);
registry.addResourceHandler("static/**")
.addResourceLocations("/static/");
}
}
代码分析
此处重点讲解 addResourceHandlers
addResourceHandlers自定义静态资源路径
文件结构如下