欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Spring Boot 實(shí)現(xiàn)圖片上傳并回顯功能

 更新時(shí)間:2021年07月05日 17:21:56   作者:Mr_YMX  
本篇文章給大家分享Spring Boot 實(shí)現(xiàn)圖片上傳并回顯功能,文中通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友參考下吧

一、常規(guī)形式

1 項(xiàng)目結(jié)構(gòu)

2 配置文件及環(huán)境設(shè)置

(1)配置文件

# 應(yīng)用服務(wù) WEB 訪問(wèn)端口
server.port=8080
# spring 靜態(tài)資源掃描路徑
spring.resources.static-locations=classpath:/static/
# 訪問(wèn)template下的html文件需要配置模板
spring.thymeleaf.prefix.classpath=classpath:/templates/
# 是否啟用緩存
spring.thymeleaf.cache=false
# 模板文件后綴
spring.thymeleaf.suffix=.html
# 模板文件編碼
spring.thymeleaf.encoding=UTF-8
#上傳的絕對(duì)路徑
file.upload.path=G://images/     #最關(guān)鍵#
#絕對(duì)路徑下的相對(duì)路徑
file.upload.path.relative=/images/**      #最關(guān)鍵#
#設(shè)置文件最大值
spring.servlet.multipart.max-file-size=5MB

在相關(guān)路徑新建文件夾

[外鏈圖片轉(zhuǎn)存失敗,源站可能有防盜鏈機(jī)制,建議將圖片保存下來(lái)直接上傳(img-lxFge7I3-1625452749715)(C:\Users\17122\AppData\Roaming\Typora\typora-user-images\image-20201106192605478.png)]

3 代碼

(1)pom.xml

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

(2)index.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="../upload" method="post" enctype="multipart/form-data">
    <input type="file" name="file" accept="image/*">
    <br>
    <input type="text" value="">
    <input type="submit" value="上傳" class="btn btn-success">
</form>
[[${filename}]]
<br>
<img th:src="@{${filename}}" alt="圖片">
</body>
</html>

(3)TestController.java

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@Controller
public class TestController {

    /**
     * 上傳地址
     */
    @Value("${file.upload.path}")
    private String filePath;

    // 跳轉(zhuǎn)上傳頁(yè)面
    @RequestMapping("test")
    public String test() {
        return "Page";
    }

    // 執(zhí)行上傳
    @RequestMapping("upload")
    public String upload(@RequestParam("file") MultipartFile file, Model model) {
        // 獲取上傳文件名
        String filename = file.getOriginalFilename();
        // 定義上傳文件保存路徑
        String path = filePath + "rotPhoto/";
        // 新建文件
        File filepath = new File(path, filename);
        // 判斷路徑是否存在,如果不存在就創(chuàng)建一個(gè)
        if (!filepath.getParentFile().exists()) {
            filepath.getParentFile().mkdirs();
        }
        try {
            // 寫入文件
            file.transferTo(new File(path + File.separator + filename));
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 將src路徑發(fā)送至html頁(yè)面
        model.addAttribute("filename", "/images/rotPhoto/" + filename);
        return "index";
    }
}

(4)MyWebAppConfigurer

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 資源映射路徑
 */
@Configuration
public class MyWebAppConfigurer implements WebMvcConfigurer {

    /**
     * 上傳地址
     */
    @Value("${file.upload.path}")
    private String filePath;
    /**
     * 顯示相對(duì)地址
     */
    @Value("${file.upload.path.relative}")
    private String fileRelativePath;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler(fileRelativePath).
                addResourceLocations("file:/" + filePath);
    }
}

4 測(cè)試

[外鏈圖片轉(zhuǎn)存失敗,源站可能有防盜鏈機(jī)制,建議將圖片保存下來(lái)直接上傳(img-HU02Yilv-1625452749717)(C:\Users\17122\AppData\Roaming\Typora\typora-user-images\image-20201106200633411.png)]

二、增加異步操作

1 前端ajax

<div class="modal-body">
     <form method="post" enctype="multipart/form-data">
        <input type="file" name="file" id="img">
        <input type="button" value="上傳" class="btn btn-outline-primary" onclick="uploadFile()"
                               style="width: 30%;">
     </form>
</div>
<script>
//上傳文件
function uploadFile() {
    //formData里面存儲(chǔ)的數(shù)據(jù)形式,一對(duì)key/value組成一條數(shù)據(jù),key是唯一的,一個(gè)key可能對(duì)應(yīng)多個(gè)value
    var myform = new FormData();
    // 此時(shí)可以調(diào)用append()方法來(lái)添加數(shù)據(jù)
    myform.append('file', $("#img")[0].files[0]);
    //驗(yàn)證不為空
    var file = $("#img")[0].files[0];
    if (file == null) {
        alert("請(qǐng)選擇文件");
        return false;
    } else {
        $.ajax({
            url: "/user/upLoad",
            type: "POST",
            data: myform,
            async: false,
            contentType: false,
            processData: false,
            success: function (result) {
                console.log(result);
                alert("上傳成功!");
                $("#div_show_img").html("<img id='input_img' src='" + result + "'>");
                $("#imgPath").attr("value", result);
                $("#div_upload").removeClass("show");
            },
            error: function (data) {
                alert("系統(tǒng)錯(cuò)誤");
            }
        });
    }
}
</script>

2 后端Controller

@ResponseBody
@RequestMapping("/upLoad")
public String upLoadImage(@RequestParam("file") MultipartFile file) {
    // 獲取上傳文件名
    String filename = file.getOriginalFilename();
    String suffixName = filename.substring(filename.lastIndexOf("."));
    // 定義上傳文件保存路徑
    String path = filePath + "images/";
    //生成新的文件名稱
    String newImgName = UUID.randomUUID().toString() + suffixName;
    // 新建文件
    File filepath = new File(path, newImgName);
    // 判斷路徑是否存在,如果不存在就創(chuàng)建一個(gè)
    if (!filepath.getParentFile().exists()) {
        filepath.getParentFile().mkdirs();
    }
    try {
        // 寫入文件
        file.transferTo(new File(path + File.separator + newImgName));
    } catch (IOException e) {
        e.printStackTrace();
    }
    return "/images/images/" + newImgName;
}

到此這篇關(guān)于Spring Boot 實(shí)現(xiàn)圖片上傳并回顯功能的文章就介紹到這了,更多相關(guān)Spring Boot上傳圖片回顯內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Java驗(yàn)證碼圖片生成代碼

    Java驗(yàn)證碼圖片生成代碼

    這篇文章主要為大家詳細(xì)介紹了Java驗(yàn)證碼圖片生成代碼,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2017-03-03
  • 淺談Java中的LinkedHashSet哈希鏈表

    淺談Java中的LinkedHashSet哈希鏈表

    這篇文章主要介紹了淺談Java中的LinkedHashSet哈希鏈表,LinkedHashSet 是 Java 中的一個(gè)集合類,它是 HashSet 的子類,并實(shí)現(xiàn)了 Set 接口,與 HashSet 不同的是,LinkedHashSet 保留了元素插入的順序,并且具有 HashSet 的快速查找特性,需要的朋友可以參考下
    2023-09-09
  • SpringBoot mybatis 實(shí)現(xiàn)多級(jí)樹形菜單的示例代碼

    SpringBoot mybatis 實(shí)現(xiàn)多級(jí)樹形菜單的示例代碼

    這篇文章主要介紹了SpringBoot mybatis 實(shí)現(xiàn)多級(jí)樹形菜單的示例代碼,代碼簡(jiǎn)單易懂,對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2021-05-05
  • MyBatis快速入門之環(huán)境搭建和單表映射

    MyBatis快速入門之環(huán)境搭建和單表映射

    一說(shuō)起對(duì)象關(guān)系映射框架,大家第一時(shí)間想到的肯定是Hibernate。Hibernate作為一個(gè)著名的框架,功能十分強(qiáng)大。但是由于Hibernate如此強(qiáng)大的功能,導(dǎo)致了它的缺點(diǎn)。好吧,不多說(shuō)了,具體詳情大家通過(guò)本文一起學(xué)習(xí)吧
    2017-03-03
  • SpringBoot+MyBatis實(shí)現(xiàn)登錄案例

    SpringBoot+MyBatis實(shí)現(xiàn)登錄案例

    前端時(shí)間在網(wǎng)上看到有朋友在學(xué)習(xí)springboot項(xiàng)目的搭建過(guò)程,今天就抽空給大家分享一個(gè)案例幫助大家學(xué)習(xí)SpringBoot+MyBatis實(shí)現(xiàn)登錄功能,具體實(shí)現(xiàn)代碼跟隨小編一起看看吧
    2021-06-06
  • Java實(shí)現(xiàn)加鹽算法的兩種方法

    Java實(shí)現(xiàn)加鹽算法的兩種方法

    數(shù)據(jù)安全是一個(gè)重要的問(wèn)題,本文主要介紹了Java實(shí)現(xiàn)加鹽算法的兩種方法,具有一定的參考價(jià)值,感興趣的可以了解一下
    2024-02-02
  • 使用Java實(shí)現(xiàn)動(dòng)態(tài)生成MySQL數(shù)據(jù)庫(kù)

    使用Java實(shí)現(xiàn)動(dòng)態(tài)生成MySQL數(shù)據(jù)庫(kù)

    這篇文章主要為大家詳細(xì)介紹了如何使用Java實(shí)現(xiàn)動(dòng)態(tài)生成MySQL數(shù)據(jù)庫(kù),文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下
    2024-02-02
  • Mybatis實(shí)體類屬性與數(shù)據(jù)庫(kù)不一致解決方案

    Mybatis實(shí)體類屬性與數(shù)據(jù)庫(kù)不一致解決方案

    這篇文章主要介紹了Mybatis實(shí)體類屬性與數(shù)據(jù)庫(kù)不一致解決方案,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-10-10
  • 七個(gè)Spring核心模塊詳解

    七個(gè)Spring核心模塊詳解

    這篇文章主要為大家詳細(xì)介紹了七個(gè)Spring的核心模塊,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2018-03-03
  • springboot加載注入bean的幾種方式

    springboot加載注入bean的幾種方式

    本文主要介紹了springboot加載注入bean的幾種方式,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2024-08-08

最新評(píng)論