千家信息网

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

发表于:2024-11-16 作者:千家信息网编辑
千家信息网最后更新 2024年11月16日,本篇内容介绍了"如何利用springboot、thymeleaf和jquery实现多文件图片上传功能"的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处
千家信息网最后更新 2024年11月16日如何利用springboot、thymeleaf和jquery实现多文件图片上传功能

本篇内容介绍了"如何利用springboot、thymeleaf和jquery实现多文件图片上传功能"的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

            上传页        


如上传图片:会展示最后一个上传的图片:

下载文件名:
# 文件路径, 注意路径末尾一定要带上/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 */@Componentpublic 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;/** * 

* 前端控制器 *

* * @author gongxl * @since 2021-05-11 */@Controller@RequestMappingpublic 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 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); }}
    4.0.0            org.springframework.boot        spring-boot-starter-parent        2.4.5                 com.example    springboot_jxc_0511    0.0.1-SNAPSHOT    springboot_jxc_0511    Demo project for Spring Boot            1.8                            org.springframework.boot            spring-boot-starter-thymeleaf                            org.springframework.boot            spring-boot-starter-web                            mysql            mysql-connector-java            runtime                            org.projectlombok            lombok            true                            com.baomidou            mybatis-plus-boot-starter            3.4.2                            com.baomidou            mybatis-plus-generator            3.4.1                            org.apache.velocity            velocity-engine-core            2.3                            org.springframework.boot            spring-boot-starter-test            test                                    org.webjars            webjars-locator            0.40                                    org.webjars.bower            jquery            3.6.0                                    org.webjars            bootstrap            5.0.0                                    org.webjars            layui            2.5.7                                                    org.springframework.boot                spring-boot-maven-plugin                                                                                        org.projectlombok                            lombok                                                                                    

"如何利用springboot、thymeleaf和jquery实现多文件图片上传功能"的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注网站,小编将为大家输出更多高质量的实用文章!

0