SpringMVC多文件上传

这篇具有很好参考价值的文章主要介绍了SpringMVC多文件上传。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

一、文件上传

1.1 导入pom依赖

 <commons-fileupload.version>1.3.3</commons-fileupload.version>
   
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>${commons-fileupload.version}</version>
    </dependency>

1.2 配置文件上传解析器

在spring-mvc.xml文件中添加文件上传解析器。

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <!-- 必须和用户JSP 的pageEncoding属性一致,以便正确解析表单的内容 -->
    <property name="defaultEncoding" value="UTF-8"></property>
    <!-- 文件最大大小(字节) 1024*1024*50=50M-->
    <property name="maxUploadSize" value="52428800"></property>
    <!--resolveLazily属性启用是为了推迟文件解析,以便捕获文件大小异常-->
    <property name="resolveLazily" value="true"/>
</bean>

这段代码是一个Spring框架的配置,用于处理文件上传功能。它定义了一个名为multipartResolver的Bean,使用org.springframework.web.multipart.commons.CommonsMultipartResolver类来处理文件上传。其中设置了默认的编码方式为UTF-8,文件的最大大小为50MB,并启用了懒解析模式。这段代码的作用是配置文件上传的相关参数。

1.3 设置文件上传表单

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <base href="${pageContext.request.contextPath }">
    <title>文件上传</title>
</head>
<body>
<form action="/file/upload" method="post" enctype="multipart/form-data">
    <label>编号:</label><input type="text" name="id" readonly="readonly" value="${param.id}"/><br/>
    <label>图片:</label><input type="file" name="imgFile"/><br/>
    <input type="submit" value="上传图片"/>
</form>
</body>
</html>

1.4 实现文件上传

(1) 设计表
SpringMVC多文件上传,java,spring
(2) 配置generatorConfig.xml,并生成代码

   <table schema="" tableName="file_upload" domainObjectName="UploadFile"
               enableCountByExample="false" enableDeleteByExample="false"
               enableSelectByExample="false" enableUpdateByExample="false">
        </table>



(3) 创建业务层

(4) 配置resource.properties

#本地路径
dir=D:/upload/
#服务器路径
server=/upload/

(5) 配置文件读取工具类

package com.xqx.utils;
 
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
 

public class PropertiesUtil {
 
    public static String getValue(String key) throws IOException {
        Properties p = new Properties();
        InputStream in = PropertiesUtil.class.getResourceAsStream("/resource.properties");
        p.load(in);
        return p.getProperty(key);
    }
}

(6) 配置项目与映射地址
SpringMVC多文件上传,java,spring
(7) 编写控制器

package com.xqx.web;
 
import com.xqx.biz.UploadFileBiz;
import com.xqx.model.UploadFile;
import com.xqx.utils.PageBean;
import com.xqx.utils.PropertiesUtil;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
 
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;
 

@Controller
@RequestMapping("/file")
public class UploadFileController {
    @Autowired
    private UploadFileBiz UploadFileBiz;
 
    /*新增方法*/
    @RequestMapping("/add")
    public String save(UploadFile UploadFile, HttpServletRequest request) {
        UploadFileBiz.insertSelective(UploadFile);
        return "redirect:list";
    }
 
    /*删除方法*/
    @RequestMapping("/del/{id}")
    public String del(@PathVariable("id") Integer id) {
        UploadFileBiz.deleteByPrimaryKey(id);
        return "redirect:/file/list";
    }
 
    /*修改方法*/
    @RequestMapping("/edit")
    public String edit(UploadFile UploadFile, HttpServletRequest request) {
        UploadFileBiz.updateByPrimaryKeySelective(UploadFile);
        return "redirect:list";
    }
 
    /*查询方法*/
    @RequestMapping("/list")
    public String list(UploadFile UploadFile, HttpServletRequest request) {
        PageBean pageBean = new PageBean();
        pageBean.setRequest(request);
        List<UploadFile> UploadFiles = UploadFileBiz.listPager(UploadFile, pageBean);
//        ModelAndView modelAndView = new ModelAndView();
//        modelAndView.addObject("UploadFiles", UploadFiles);
//        modelAndView.addObject("pageBean", pageBean);
//        modelAndView.setViewName("UploadFile/list");
        request.setAttribute("UploadFiles", UploadFiles);
        request.setAttribute("pageBean", pageBean);
        return "file/list";
    }
 
    /*数据回显*/
    @RequestMapping("/preSave")
    public String preSave(UploadFile UploadFile, HttpServletRequest request) {
        if (UploadFile != null && UploadFile.getId() != null && UploadFile.getId() != 0) {
            UploadFile img = UploadFileBiz.selectByPrimaryKey(UploadFile.getId());
            request.setAttribute("img", img);
        }
        return "file/edit";
    }
 
    /*图片上传*/
    @RequestMapping("upload")
    public String upload(UploadFile img,MultipartFile imgFile) throws IOException {
        //读取配置文夹本地路径和服务器路径
        String dir = PropertiesUtil.getValue("dir");
        String server = PropertiesUtil.getValue("server");
 
        //利用MultipartFile类接受前端传递到后台的文件
        System.out.println("文件名:"+imgFile.getOriginalFilename());
        System.out.println("文件类型:"+imgFile.getContentType());
 
        //将文件转成流写入到服务器
        FileUtils.copyInputStreamToFile(imgFile.getInputStream(),new File(dir+imgFile.getOriginalFilename()));
 
        //通过对象将图片保存到数据库
        img.setImg(server+imgFile.getOriginalFilename());
        UploadFileBiz.updateByPrimaryKeySelective(img);
 
        return "redirect:list";
    }
}

(8) 编写jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="w" uri="http://jsp.xqx.cn" %>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <link
            href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.css"
            rel="stylesheet">
    <script
            src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.0/js/bootstrap.js"></script>
    <base href="${pageContext.request.contextPath }">
    <title></title>
    <style type="text/css">
        .page-item input {
            padding: 0;
            width: 40px;
            height: 100%;
            text-align: center;
            margin: 0 6px;
        }
 
        .page-item input, .page-item b {
            line-height: 38px;
            float: left;
            font-weight: 400;
        }
 
        .page-item.go-input {
            margin: 0 10px;
        }
    </style>
</head>
<body>
<form class="form-inline"
      action="/file/list" method="post">
    <div class="form-group mb-2">
        <input type="text" class="form-control-plaintext" name="name"
               placeholder="请输入用户名称">
    </div>
    <button type="submit" class="btn btn-primary mb-2">查询</button>
    <a class="btn btn-primary mb-2" href="/file/preSave">新增</a>
</form>
 
<table class="table table-striped">
    <thead>
    <tr>
        <th scope="col">ID</th>
        <th scope="col">用户</th>
        <th scope="col">图片</th>
    </tr>
    </thead>
    <tbody>
    <c:forEach var="i" items="${uploadImgs }">
        <tr>
            <td>${i.id }</td>
            <td>${i.name }</td>
            <td>
                <img src="${i.img }" style="width: 200px;height: 100px;">
            </td>
            <td>
                <a href="/file/preSave?id=${i.id}">修改</a>
                <a href="/file/del/${i.id}">删除</a>
                <a href="/page/file/upload?id=${i.id}">图片上传</a>
                <a href="/file/download?id=${i.id}">图片下载</a>
            </td>
        </tr>
    </c:forEach>
    </tbody>
</table>
<!-- 这一行代码就相当于前面分页需求前端的几十行了 -->
<w:page pageBean="${pageBean }"></w:page>
 
</body>
</html>

SpringMVC多文件上传,java,spring

二、文件下载

根据传入的文件id查询对应的文件信息,然后根据文件路径读取文件内容,并将文件内容和设置好的HTTP头信息封装成一个ResponseEntity对象,最后返回给客户端进行文件下载。

   @RequestMapping("/download")
    public ResponseEntity<byte[]> download(UploadImg uploadImg, HttpServletRequest req){
        try {
            //先根据文件id查询对应图片信息
            UploadImg img = this.uploadImgBiz.selectByPrimaryKey(uploadImg.getId());
            String diskPath = PropertiesUtil.getValue("dir");
            String reqPath = PropertiesUtil.getValue("server");
            //上面获取的数据库地址,需要转换才能下载成本地路径
            String realPath = img.getImg().replace(reqPath,diskPath);
            String fileName = realPath.substring(realPath.lastIndexOf("/")+1);
            //下载关键代码
            File file=new File(realPath);
            HttpHeaders headers = new HttpHeaders();//http头信息
            String downloadFileName = new String(fileName.getBytes("UTF-8"),"iso-8859-1");//设置编码
            headers.setContentDispositionFormData("attachment", downloadFileName);
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            //MediaType:互联网媒介类型  contentType:具体请求中的媒体类型信息
            return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.OK);
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

三、多文件上传

//多文件上传
    @RequestMapping("/uploads")
    public String uploads(HttpServletRequest req, Music music, MultipartFile[] files){
        try {
            StringBuffer sb = new StringBuffer();
            for (MultipartFile cfile : files) {
                //思路:
                //1) 将上传图片保存到服务器中的指定位置
                String dir = PropertiesUtil.getValue("dir");
                String server = PropertiesUtil.getValue("server");
                String filename = cfile.getOriginalFilename();
                FileUtils.copyInputStreamToFile(cfile.getInputStream(),new File(dir+filename));
                sb.append(filename).append(",");
            }
            System.out.println(sb.toString());
 
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "redirect:list";
    }

SpringMVC多文件上传,java,spring

四、JRebel的使用

下载
SpringMVC多文件上传,java,spring文章来源地址https://www.toymoban.com/news/detail-706361.html

到了这里,关于SpringMVC多文件上传的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • SpringMVC的文件上传

    文件上传客户端表单需要满足: 表单项type=“file” 表单的提交方式是post 表单的enctype属性是多部分表单形式,及enctype=“multipart/form-data” 添加依赖 配置多媒体解析器 后台程序 完成文件上传 多文件上传,只需要将页面修改为多个文件上传项,将方法参数MultipartFile类型修改

    2024年02月02日
    浏览(26)
  • SpringMVC 文件上传和下载

    Spring MVC 提供了简单而强大的文件上传和下载功能。 下面是对两者的简要介绍: 文件上传: 在Spring MVC中进行文件上传的步骤如下: 在表单中设置 enctype=“multipart/form-data”,这样浏览器会将表单数据以二进制流的形式进行传输。 在控制器方法中,使用 @RequestParam 注解来接收

    2024年01月17日
    浏览(33)
  • SpringMVC实现文件上传&下载(2)

    文件上传步骤 第一步:由于SpringMVC使用的是commons-fileupload实现,故将其组件引入项目中,这里用到的是commons-fileupload-1.2.1.jar和commons-io-1.3.2.jar。 第二步:spring-mvx中配置MultipartResolver处理器。可在此加入对上传文件的属性限制。 第三步:在Controller的方法中添加MultipartFile参数。

    2024年03月09日
    浏览(45)
  • SpringMVC之文件上传和下载

    实现下载文件和上传文件的功能。 使用ResponseEntity实现下载文件的功能 文件上传要求form表单的请求方式必须为post,并且添加属性enctype=“multipart/form-data” SpringMVC中将上传的文件封装到MultipartFile对象中,通过此对象可以获取文件相关信息。 步骤: 添加依赖 在SpringMVC的配置

    2024年02月10日
    浏览(49)
  • SpringMVC实现表单文件的上传

    Content-Type 类型 HTTP的Content-Type是一种标识HTTP请求或响应中包含的实体的媒体类型的头部字段。它指示了数据的类型,使接收方能够正确处理数据。以下是一些常见的Content-Type类型:text/plain:纯文本,没有特定格式。 text/html:HTML文档。 text/css:Cascading Style Sheets (CSS)。 text/j

    2024年02月07日
    浏览(28)
  • SpringMVC实现多文件上传源码

    2024年03月09日
    浏览(50)
  • SpringMVC 实现文件的上传和下载

    SpringMVC 是一个基于 Java 的 Web 框架,它提供了方便的文件上传和下载功能。下面是它的实现原理简要描述: 文件上传: 客户端通过表单(HTML 的 标签)将文件选择并提交到服务器。 服务器接收到请求后,SpringMVC 会将字节流形式的文件内容封装成 MultipartFile 对象。 SpringMVC 使

    2024年02月05日
    浏览(38)
  • SpringMVC下半篇之文件上传

    编写controller 在index.jsp里面定义超链接

    2024年01月20日
    浏览(29)
  • SpringMVC Day 08 : 文件上传下载

    文件上传和下载是 Web 开发中的重要环节,但它们往往不那么容易实现。幸运的是,Spring MVC 提供了一套简单而又强大的解决方案,让我们可以专注于业务逻辑,而不必过多关注底层的文件处理细节。 在本篇博客中,我们将学习如何利用 Spring MVC 实现文件上传和下载功能。首

    2024年02月06日
    浏览(30)
  • 【SpringMVC】文件上传与下载、JREBEL使用

    目录 一、引言 二、文件的上传 1、单文件上传 1.1、数据表准备 1.2、添加依赖 1.3、配置文件 1.4、编写表单 1.5、编写controller层 2、多文件上传 2.1、编写form表单 2.2、编写controller层 2.3、测试 三、文件下载 四、JREBEL使用 1、下载注册 2、离线设置 为什么要使用文件的上传下载?

    2024年02月07日
    浏览(30)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包