其他分享
首页 > 其他分享> > SpringBoot上传图片项目

SpringBoot上传图片项目

作者:互联网

上传图片到服务器,并返回路径

maven的配置

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.5.5</version>
    <relativePath/> <!-- lookup parent from repository -->
  </parent>
  <groupId>org.example</groupId>
  <artifactId>file-upload</artifactId>
  <version>1.0-SNAPSHOT</version>

  <name>file-upload</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
    <java.version>1.8</java.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <!--上传图片需要的依赖-->
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.4</version>
    </dependency>
  </dependencies>

  <build>
    <finalName>file-upload</finalName>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </build>
</project>

配置文件的配置

application.yml

server:
  port: 8181
spring:
  profiles:
    active: pro
  # 修改文件上传的大小
  servlet:
    multipart:
      enabled: true
      file-size-threshold: 0
      max-file-size: 100MB
      max-request-size: 100MB

application-dev.yml

server:
  port: 8181
#上传文件的配置
upload:
  # 上传服务器的位置
  filePath: /Users/wanglichao/Desktop/temp/upload/test/
  # 返回的url路径
  fileUrl: /Users/wanglichao/Desktop/temp/upload/test/

application-pro.yml

server:
  port: 8181

upload:
  filePath: /myapp/upload/image/
  fileUrl: http://ip服务器:8083/image/

启动类

App.java

package com.wlc;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * Hello world!
 */
@SpringBootApplication
public class App {
    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}

工具类

JsonResult.java统一返回类

package com.wlc.util;

/**
 * @author 王立朝
 * @description 统一返回类
 * @date 2021-12-21 21:56:22
 */
public class JsonResult<T> {

    private Integer code;
    private String msg;
    private Object data;

    public JsonResult(Integer code, String msg, Object data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    public JsonResult() {
    }


    public com.wlc.util.JsonResult<T> success(Object data){
        com.wlc.util.JsonResult jsonResult = new com.wlc.util.JsonResult<T>();
        jsonResult.setCode(200);
        jsonResult.setMsg("成功了!");
        jsonResult.setData(data);
        return jsonResult;
    }
    public com.wlc.util.JsonResult<T> success(){
        com.wlc.util.JsonResult jsonResult = new com.wlc.util.JsonResult<T>();
        jsonResult.setCode(200);
        jsonResult.setMsg("成功了!");
        return jsonResult;
    }
    public com.wlc.util.JsonResult<T> error(Integer code, String msg, Object obj){
        return new com.wlc.util.JsonResult<T>(code,msg,obj);
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }
}

service接口

UploadService.java

package com.wlc.service;
import com.wlc.util.JsonResult;
import org.springframework.web.multipart.MultipartFile;
/**
 * @author 王立朝
 * @date 2022/3/9
 * @description: 上传服务接口
 */
public interface UploadService {
    /**
     * 上传服务接口
     * @param multipartFile
     * @return
     */
    JsonResult upload(MultipartFile multipartFile);
}

service接口实现类

UploadServiceImpl.java

package com.wlc.service.impl;

import com.wlc.service.UploadService;
import com.wlc.util.JsonResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/**
 * @author 王立朝
 * @date 2022/3/9
 * @description:
 */
@Service
public class UploadServiceImpl implements UploadService {
    private static final Logger logger = LoggerFactory.getLogger(UploadServiceImpl.class);

    /**
     * 文件上传的路径
     */
    @Value("${upload.filePath}")
    private String filePath;
    /**
     * 文件返回前台的路径
     */
    @Value("${upload.fileUrl}")
    private String fileUrl;

    /**
     * 上传服务接口
     *
     * @param multipartFile
     * @return
     */
    @Override
    public JsonResult upload(MultipartFile multipartFile) {
        JsonResult jsonResult;
        if (!multipartFile.isEmpty()) {
            try {
                logger.info("开始上传功能。。。。");
                // 获取当前日期
                String date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                File file = new File(filePath + date);
                if(!file.exists()){
                    file.mkdir();
                }
                // 修改文件名称
                String fileName = setFileName(multipartFile.getOriginalFilename());
                multipartFile.transferTo(new File(filePath + date + "/" + fileName));
                logger.info(filePath + multipartFile.getOriginalFilename());
                jsonResult = new JsonResult(200, "上传成功", fileUrl + date + "/" + fileName);
                logger.info("结束上传功能。。。。");

            } catch (Exception e) {
                e.printStackTrace();
                logger.error("网络异常");
                jsonResult = new JsonResult(500, "网络异常", "");
            }
        } else {
            logger.error("上传失败!");
            jsonResult = new JsonResult(404, "上传失败", "");
        }
        return jsonResult;
    }

    private String setFileName(String originalFilename) {
        // 获取文件的后缀名称
        String substring = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        return UUID.randomUUID() + "." + substring;
    }
}

controller控制器

UploadController.java

package com.wlc.controller;
import com.wlc.service.UploadService;
import com.wlc.util.JsonResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

/**
 * @author 王立朝
 * @description 上传控制类
 * @date 2021-12-21 21:52:06
 */
@RestController
public class UploadController {

    @Resource
    private UploadService uploadService;

    @PostMapping("/api/upload")
    public JsonResult upload(@RequestParam("userHeaderPicture") MultipartFile multipartFile) {
        return new JsonResult().success(uploadService.upload(multipartFile));
    }

    @GetMapping("/hello")
    public String hello() {
        return "hello world!";
    }

}

目录结构图

├── pom.xml
├── src
│   ├── main
│   │   ├── java
│   │   │   └── com
│   │   │       └── wlc
│   │   │           ├── App.java
│   │   │           ├── controller
│   │   │           │   └── UploadController.java
│   │   │           ├── service
│   │   │           │   ├── UploadService.java
│   │   │           │   └── impl
│   │   │           │       └── UploadServiceImpl.java
│   │   │           └── util
│   │   │               └── JsonResult.java
│   │   └── resources
│   │       ├── application-dev.yml
│   │       ├── application-pro.yml
│   │       └── application.yml

生成项目结构图的命令

tree > tree3.text
https://gitee.com/wanglichaohahaha/gitee-image-bed/raw/master/uploadImg/2022-03/1647781077341_585032be-7173-4ce5-b89a-afcb076df26e.png

标签:JsonResult,SpringBoot,com,org,import,wlc,上传,public,图片
来源: https://www.cnblogs.com/wanglichaoya/p/16031472.html