当前位置:   article > 正文

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
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

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

图片存放文件夹

  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
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  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);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53

这是我的 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
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  1. 大功告成! 如果对您有帮助的话,还请动动小手点个赞
    声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/1005569
推荐阅读
相关标签