溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

SpringBoot中怎么實(shí)現(xiàn)圖片上傳

發(fā)布時(shí)間:2021-06-17 13:51:39 來源:億速云 閱讀:243 作者:Leah 欄目:編程語言

這篇文章將為大家詳細(xì)講解有關(guān)SpringBoot中怎么實(shí)現(xiàn)圖片上傳,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個(gè)參考,希望大家閱讀完這篇文章后對(duì)相關(guān)知識(shí)有一定的了解。

1、先貼圖片上傳工具類

package com.prereadweb.utils;
 
import java.io.File;
import java.io.FileOutputStream;
import java.util.UUID;
 

public class FileTool {
 
  /**
   * @Function: 圖片上傳
   * @author:  YangXueFeng
   * @Date:   2019/4/18 14:13
   */
  public static void uploadFiles(byte[] file, String filePath, String fileName) throws Exception {
    File targetFile = new File(filePath);
    if (!targetFile.exists()) {
      targetFile.mkdirs();
    }
    FileOutputStream out = new FileOutputStream(filePath + fileName);
    out.write(file);
    out.flush();
    out.close();
  }
 
  /**
   * @Function: 創(chuàng)建新的文件名
   * @author:  YangXueFeng
   * @Date:   2019/4/17 17:57
   */
  public static String renameToUUID(String fileName) {
    return UUID.randomUUID() + "." + fileName.substring(fileName.lastIndexOf(".") + 1);
  }
}

2、contoller層

  @PostMapping("/postfile")
  public Object fileUpload(@RequestParam(value = "userImg", required = false) MultipartFile file, @RequestParam(value = "userId", required = false) Long userId) {
    return personalService.fileUpload(file, userId);
  }

此處提一下@RequestParam注解

value:前臺(tái)所傳參數(shù)的名稱

required:它有兩個(gè)參數(shù),true/false,默認(rèn)是true,如果設(shè)置的是true的,客戶端如果傳值為空的話,訪問此接口會(huì)報(bào)500異常,如果是false的話,客戶端傳值為空,會(huì)默認(rèn)給參數(shù)賦值null

3、service層

  @Override
  public Map<String, Object> fileUpload(MultipartFile file, Long userId) {
    Map<String, Object> map = new HashMap<>();
    if (Util.isEmpty(file)) {
      System.out.println("文件為空空");
      map.put("code", UserStatusEnum.EMPTY.intKey());
      map.put("msg", UserStatusEnum.EMPTY.value());
      return map;
    }
    UserEntity user = userMapper.fetchUser(userId);
    if(Util.isEmpty(user)){
      map.put("code", UserStatusEnum.USER_NOT_EXISTENCE.intKey());
      map.put("msg", UserStatusEnum.USER_NOT_EXISTENCE.value());
      return map;
    }
 
    String fileName = file.getOriginalFilename();
    fileName = FileTool.renameToUUID(fileName);
    try {
      FileTool.uploadFiles(file.getBytes(), uploadConfig.getUploadPath(), fileName);
    } catch (Exception e) {
    }
    if (Util.isEmpty(fileName)) {
      map.put("code", UserStatusEnum.USER_NOT_EXISTENCE.intKey());
      map.put("msg", UserStatusEnum.USER_NOT_EXISTENCE.value());
      return map;
    }
 
    Map<String, Object> returnMap = new HashMap<>();
    String url = "/static/" + fileName;
    updateUrl(userId, url);
    returnMap.put("imageUrl", url);
    map.put("code", UserStatusEnum.SUCCESS.intKey());
    map.put("msg", UserStatusEnum.SUCCESS.value());
    map.put("data", returnMap);
    return map;
  }

4、設(shè)置圖片訪問路徑映射

preread: 
   #文件上傳目錄(注意Linux和Windows上的目錄結(jié)構(gòu)不同) 
   uploadPath: E:/image/

5、配置文件上傳路徑

package com.prereadweb.config.upload;
 
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
 

@Component
@ConfigurationProperties(prefix="preread")
public class PreReadUploadConfig {
 
  //上傳路徑
  private String uploadPath;
 
  public String getUploadPath() {
    return uploadPath;
  }
 
  public void setUploadPath(String uploadPath) {
    this.uploadPath = uploadPath;
  }
}

6、配置映射路徑

package com.prereadweb.config.upload;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
 

@ComponentScan
@Configuration
public class WebConfigurer extends WebMvcConfigurerAdapter {
 
  @Autowired
  PreReadUploadConfig uploadConfig;
  @Override
  public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/static/**").addResourceLocations("file:///"+uploadConfig.getUploadPath());
  }
}

7、此處需要導(dǎo)入一個(gè)jar報(bào)

<!-- 配置 -->
 <dependency>
  <groupId> org.springframework.boot </groupId>
  <artifactId> spring-boot-configuration-processor </artifactId>
  <optional> true </optional>
</dependency>

8、postman測(cè)試接口

SpringBoot中怎么實(shí)現(xiàn)圖片上傳

9、此時(shí)配置完成

圖片的存儲(chǔ)路徑在:E:/image/

訪問路徑:http://127.0.0.1:8080/static/0fa7481d-4fec-42c3-a716-514feff73707.jpg

關(guān)于SpringBoot中怎么實(shí)現(xiàn)圖片上傳就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI