1. 程式人生 > 其它 >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