前端axios发送图片以及java springboot接受并保存文件简单示例

文章自用,仅作参考

本文章记录基于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自定义静态资源路径
文件结构如下
这是文件结构

注意:上述路径都是写死了的,请读者根据自身需求,修改路径以及文件命名。

效果请自行尝试,打开浏览器控制台可以查看返回的文件URL

感谢浏览

  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值