温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何利用springboot、thymeleaf和jquery实现多文件图片上传功能

发布时间:2021-09-06 17:51:07 来源:亿速云 阅读:187 作者: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