中文字幕av专区_日韩电影在线播放_精品国产精品久久一区免费式_av在线免费观看网站

溫馨提示×

溫馨提示×

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

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

如何利用springboot、thymeleaf和jquery實現多文件圖片上傳功能

發布時間:2021-09-06 17:51:07 來源:億速云 閱讀:205 作者:chen 欄目:編程語言

本篇內容介紹了“如何利用springboot、thymeleaf和jquery實現多文件圖片上傳功能”的有關知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領大家學習一下如何處理這些情況吧!希望大家仔細閱讀,能夠學有所成!

如何利用springboot、thymeleaf和jquery實現多文件圖片上傳功能

<!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是寫死在這里,一定不要忘記尾部的/或者\\,這樣才能讀取其目錄下的文件
        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 {
        // 發送給客戶端的數據
        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()){
            //不存在就創建一個
            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();
        // 設置信息給客戶端不解析
        String type = fileName.substring(fileName.lastIndexOf(".")+1);
        // 設置contenttype,即告訴客戶端所發送的數據屬于什么類型
        response.setHeader("Content-type",type);
        // 設置編碼
        String hehe = new String(fileName.getBytes("utf-8"), "iso-8859-1");
        // 設置擴展頭,當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實現多文件圖片上傳功能”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業相關的知識可以關注億速云網站,小編將為大家輸出更多高質量的實用文章!

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

开封市| 卢湾区| 黔东| 屏南县| 探索| 财经| 金阳县| 荃湾区| 马关县| 富民县| 黔西县| 汪清县| 灯塔市| 阜新市| 永济市| 尉犁县| 山东省| 黄浦区| 周宁县| 西华县| 麻城市| 和田县| 五峰| 崇明县| 道真| 汝城县| 措勤县| 阿拉善盟| 喀什市| 五河县| 永昌县| 观塘区| 萍乡市| 临潭县| 赤峰市| 库车县| 绥阳县| 蒙山县| 漾濞| 延安市| 洞头县|