如何利用springboot、thymeleaf和jquery實(shí)現(xiàn)多文件圖片上傳功能

本篇內(nèi)容介紹了“如何利用springboot、thymeleaf和jquery實(shí)現(xiàn)多文件圖片上傳功能”的有關(guān)知識,在實(shí)際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細(xì)閱讀,能夠?qū)W有所成!

成都創(chuàng)新互聯(lián)公司服務(wù)項(xiàng)目包括華安網(wǎng)站建設(shè)、華安網(wǎng)站制作、華安網(wǎng)頁制作以及華安網(wǎng)絡(luò)營銷策劃等。多年來,我們專注于互聯(lián)網(wǎng)行業(yè),利用自身積累的技術(shù)優(yōu)勢、行業(yè)經(jīng)驗(yàn)、深度合作伙伴關(guān)系等,向廣大中小型企業(yè)、政府機(jī)構(gòu)等提供互聯(lián)網(wǎng)行業(yè)的解決方案,華安網(wǎng)站推廣取得了明顯的社會效益與經(jīng)濟(jì)效益。目前,我們服務(wù)的客戶以成都為中心已經(jīng)輻射到華安省份的部分城市,未來相信會繼續(xù)擴(kuò)大服務(wù)區(qū)域并繼續(xù)獲得客戶的支持與信任!

如何利用springboot、thymeleaf和jquery實(shí)現(xiàn)多文件圖片上傳功能

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <link th:href="@{favicon.ico}"  rel="shortcut icon"/>
    <title>上傳頁</title>
    <script th:src="@{/webjars/jquery/dist/jquery.js}"  type="text/javascript"></script>

</head>
<body>
    <div class="con">
        <form action="multiUpload" method="post" enctype="multipart/form-data">
            <input type="file" name="file"><br/>
            <input type="file" name="file"><br/>
            如上傳圖片:會展示最后一個上傳的圖片: <input type="file" name="file"><br/>
            <button type="submit">上傳</button>
        </form>

        <img th:src="${filePath}" width="300px" height="300px">
        <div th:if="${ message }">
            <h3 th:text="${ message }"/>
        </div>
    </div>
    <div>
        下載文件名:
        <input type="text" value="" id="fileName"/>
        <input type="button" value="下載"  onclick="download()"/>
        <script>
            $(document).ready(function(){
            });
            function download(){
                let fileName = $("#fileName").val();
                if(fileName){
                    window.open("http://" + window.location.host + "/download/" + fileName, '_blank')
                }else{
                    alert("輸入文件名")
                }
            }
        </script>
    </div>
</body>
</html>
# 文件路徑, 注意路徑末尾一定要帶上/
user.file.path=E:/upload/
package com.example.springboot_jxc_0511.common;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 參考:https://blog.csdn.net/sinat_34104446/article/details/100178488
 */
@Component
public class CustomWebConfiguration implements WebMvcConfigurer {
    @Value("${user.file.path}")
    private String filePath;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {

        // 注意如果filePath是寫死在這里,一定不要忘記尾部的/或者\(yùn)\,這樣才能讀取其目錄下的文件
        registry.addResourceHandler("/**").addResourceLocations(
                "classpath:/META-INF/resources/",
                "classpath:/resources/",
                "classpath:/static/",
                "classpath:/public/",
                "file:/" + filePath,
                "classpath:/webapp/");
    }
}
package com.example.springboot_jxc_0511.common;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

public class FileUtil {
    public static void download(String filename, HttpServletResponse res) throws IOException {
        // 發(fā)送給客戶端的數(shù)據(jù)
        OutputStream outputStream = res.getOutputStream();
        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        // 讀取filename
        bis = new BufferedInputStream(new FileInputStream(new File("e:/upload/" + filename)));
        int i = bis.read(buff);
        while (i != -1) {
            outputStream.write(buff, 0, buff.length);
            outputStream.flush();
            i = bis.read(buff);
        }
    }
}
package com.example.springboot_jxc_0511.common;


import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.springboot_jxc_0511.common.FileUtil;
import com.example.springboot_jxc_0511.jxc.common.Constants;
import com.example.springboot_jxc_0511.jxc.entity.Product;
import com.example.springboot_jxc_0511.jxc.entity.Sale;
import com.example.springboot_jxc_0511.jxc.entity.Users;
import com.example.springboot_jxc_0511.jxc.service.IProductService;
import com.example.springboot_jxc_0511.jxc.service.ISaleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author gongxl
 * @since 2021-05-11
 */
@Controller
@RequestMapping
public class UploadController {
    @Value("${user.file.path}")
    private String filePath;
    /**
     * @Author GongXl
     * @Description
     * @Date 2021/5/20 14:44
     * @Param [model]
     * @return java.lang.String
     **/
    @RequestMapping("/toUpload")
    public String toUpload(Model model) {
        return "upload";
    }
    /**
     * @Author GongXl
     * @Description 單文件上傳
     * @Date 2021/5/20 14:47
     * @Param [file, model]
     * @return java.lang.String
     **/
    @PostMapping("/uploadFile")
    public String upload(@RequestParam("file") MultipartFile file, Model model){
        if (file.isEmpty()){
            model.addAttribute("message", "The file is empty!");
            return "upload";
        }
        try{
            byte[] bytes = file.getBytes();
            Path path = Paths.get(filePath + file.getOriginalFilename());
            Files.write(path, bytes);
            model.addAttribute("message", "succes");
        }catch (Exception e){
            e.printStackTrace();
        }
        return "upload";
    }

    /**
     * 多文件上傳
     * @param request
     * @param model
     * @return
     */
    @PostMapping("/multiUpload")
    public String multiUpload(HttpServletRequest request, Model model) {
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
        File fileTemp =  new File(filePath);
        //判斷文件父目錄是否存在
        if(!fileTemp.exists()){
            //不存在就創(chuàng)建一個
            fileTemp.mkdirs();
        }
        for (int i = 0; i < files.size(); i++) {
            MultipartFile file = files.get(i);
            if (file.isEmpty()) {
                model.addAttribute("message", "上傳第"+i+"個文件失敗。");
            }
            String fileName = file.getOriginalFilename();

            File dest = new File(filePath + fileName);
            try {
                file.transferTo(dest);
                System.out.println(dest.getAbsolutePath());
                model.addAttribute("message", "succes");
                model.addAttribute("filePath","/"+fileName);
            } catch (IOException e) {
                model.addAttribute("message", "上傳異常");
            }
        }
        return "upload";
    }

    /**
     * 下載文件
     * @param fileName
     * @throws IOException
     */
    @RequestMapping(value = "/download/{fileName:.+}")
    public void download(@PathVariable String fileName) throws IOException {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = requestAttributes.getResponse();
        // 設(shè)置信息給客戶端不解析
        String type = fileName.substring(fileName.lastIndexOf(".")+1);
        // 設(shè)置contenttype,即告訴客戶端所發(fā)送的數(shù)據(jù)屬于什么類型
        response.setHeader("Content-type",type);
        // 設(shè)置編碼
        String hehe = new String(fileName.getBytes("utf-8"), "iso-8859-1");
        // 設(shè)置擴(kuò)展頭,當(dāng)Content-Type 的類型為要下載的類型時 , 這個信息頭會告訴瀏覽器這個文件的名字和類型。
        response.setHeader("Content-Disposition", "attachment;filename=" + hehe);
        FileUtil.download(fileName, response);
    }
}
<?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 https://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.4.5</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>springboot_jxc_0511</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot_jxc_0511</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <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>

        <dependency>
            <groupId>MySQL</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.2</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.4.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity-engine-core</artifactId>
            <version>2.3</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.webjars/webjars-locator -->
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>webjars-locator</artifactId>
            <version>0.40</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.webjars.bower/jquery -->
        <dependency>
            <groupId>org.webjars.bower</groupId>
            <artifactId>jquery</artifactId>
            <version>3.6.0</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.webjars/bootstrap -->
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>bootstrap</artifactId>
            <version>5.0.0</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.webjars/layui -->
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>layui</artifactId>
            <version>2.5.7</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

“如何利用springboot、thymeleaf和jquery實(shí)現(xiàn)多文件圖片上傳功能”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識可以關(guān)注創(chuàng)新互聯(lián)網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實(shí)用文章!

當(dāng)前名稱:如何利用springboot、thymeleaf和jquery實(shí)現(xiàn)多文件圖片上傳功能
當(dāng)前地址:http://muchs.cn/article46/ispdeg.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供域名注冊、品牌網(wǎng)站制作、標(biāo)簽優(yōu)化全網(wǎng)營銷推廣、網(wǎng)站導(dǎo)航網(wǎng)站改版

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

成都網(wǎng)站建設(shè)