web前端上传图片到Java后端,并保存到本地

web前端上传图片到Java后端,并保存到本地

解决方法:使用 springBoot 静态资源映射

  1. 在 application.yaml 配置静态资源存放路径 baseFilePath ,我这里是D:/develop/IDEA_project/blogResources/images/,可以随意更改位置
spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    druid:
      url: jdbc:mysql://127.0.0.1:3306/myblogdb
      username: root
      password: 123456
      driver-class-name: com.mysql.cj.jdbc.Driver
  servlet:
    multipart:
      max-file-size: 5MB
      max-request-size: 10MB

mybatis:
  mapper-locations: classpath:/mappers/*.xml

server:
  port: 8888
#静态资源映射
#Linux
#baseFilePath: /www/wwwroot/blogResources/images/
#windows
baseFilePath: D:/develop/IDEA_project/blogResources/images/

这是我的图片存放位置,位置必须对应上,不然访问不到图片

图片存放文件夹

  1. 在 springBoot 启动类中,添加 addResourceHandlers 配置
package com.zcm;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@MapperScan("com.zcm.mapper")
@SpringBootApplication
public class MyBlogApplication implements WebMvcConfigurer {

    public static void main(String[] args) {
        SpringApplication.run(MyBlogApplication.class, args);
    }

	//这里是读取 application.yaml 中的文件存放路径
    @Value("${baseFilePath}")
    private String basePath;

	//配置静态资源映射,意思是 当访问路径为 /images 的就会去访问这个文件夹下的文件,
	//比如 http://127.0.0.1:8888/images/717dec8a-2088-43dc-b180-7dd1fa8cac66.jpeg
	//  可以任意更改 /images ,比如 /img 都可以 ,但是 访问的时候 路径要变成的改成
	//  http://127.0.0.1:8888/img/717dec8a-2088-43dc-b180-7dd1fa8cac66.jpeg
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/images/**").addResourceLocations("file:" + basePath);
    }

}
  1. 启动 springBoot 就可以通过浏览器访问了图片资源,比如访问 http://127.0.0.1:8888/images/717dec8a-2088-43dc-b180-7dd1fa8cac66.jpeg
    访问成功
    4.接收前端的上传的图片 , 通过 /upload 接口 实现图片上传 ,并返回图片url
package com.zcm.controller;

import com.zcm.pojo.Response;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.util.UUID;

@RestController
@CrossOrigin
public class UploadController {

    @Value("${baseFilePath}")
    private String basePath;

    /**
     * 上传图片资源,使用静态资源映射
     *
     * @param webFile 文件
     * @return true/false
     */
    @PostMapping("/upload")
    public Response login(@RequestParam("file") MultipartFile webFile) {
        String imageName = webFile.getOriginalFilename();
        //有可能为空值
        if (imageName == null || imageName.isEmpty()) {
            return new Response(false);
        }
        String[] split = imageName.split("\\.");
        String imgType = split[split.length - 1];
        UUID randomUUID = UUID.randomUUID();
        String fileName = randomUUID + "." + imgType;
        String FilePath = basePath + fileName;
        try {
            File file = new File(FilePath);
            if (!file.exists()) {
                if (file.createNewFile()) {
                    System.out.println("文件 " + FilePath + " 创建成功!");
                }
                FileOutputStream fileOutputStream = new FileOutputStream(file);
                fileOutputStream.write(webFile.getBytes());
                fileOutputStream.close();
                return new Response(true, fileName);
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return new Response(false);
    }
}

这是我的 Response类 你也可以自己定义,也可以不用返回 Response,返回 String都行

public class Response {
    private Boolean state;
    private Object data;
    public Response() {
    }
    public Response(Boolean state) {
        this.state = state;
    }
    public Response(Boolean state, Object data) {
        this.state = state;
        this.data = data;
    }
    public Boolean getState() {
        return state;
    }
    public void setState(Boolean state) {
        this.state = state;
    }
    public Object getData() {
        return data;
    }
    public void setData(Object data) {
        this.data = data;
    }
}
  1. 大功告成! 如果对您有帮助的话,还请动动小手点个赞👍!😄
  • 9
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值