SpringMVC实现批量上传和下载功能

第一.jar包


        <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.3.18.RELEASE</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
        </dependency>

第二步.web.xml和主配置文件

<!DOCTYPE web-app PUBLIC
    "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
    "http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
    version="4.0">
  <display-name>Archetype Created Web Application</display-name>

  <servlet>
    <servlet-name>springMVC</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:mvc-servlet.xml</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>springMVC</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>

  <!--springmvc的过滤器   防止中文乱码-->
  <filter>
    <filter-name>EncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
  </filter>

  <filter-mapping>
    <filter-name>EncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!--1.配置注解扫描位置-->
    <context:component-scan base-package="com.hw.controller"/>
    <!--2.配置处理器映射,通过注解查找-->
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"></bean>
    <!--3.配置适配器-->
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">

    </bean>
    <!--4.配置资源视图解析-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--前缀-->
        <property name="prefix" value="/"></property>
        <!--后缀-->
        <property name="suffix" value=".jsp"></property>
    </bean>

    <!--上传文件-->
    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!--上传文件的最大大小-->
        <property name="maxUploadSize" value="17367648787"></property>
        <!--上传文件的编码-->
        <property name="defaultEncoding" value="UTF-8"></property>
    </bean>
</beans>

准备作为测试用的jsp页面

<%--
  Created by IntelliJ IDEA.
  Date: 2019/1/4
  Time: 0:22
  To change this template use File | Settings | File Templates.
--%>
<%@ page pageEncoding="utf-8" isELIgnored="false"%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<form action="up.do" enctype="multipart/form-data" method="post">
    <table>
        <tr>
            <td>请选择文件:</td>
            <td><input type="file" name="file"></td>
            <td><input type="file" name="file"></td>
            <td><input type="file" name="file"></td>
        </tr>
        <tr>
            <td>开始上传</td>
            <td><input type="submit" value="上传"></td>
        </tr>
    </table>
</form>

<%--这里只是模拟下载所以用的死数据,项目中肯定是要在数据库中取值的--%>
<a href="/download.do?filename=IDEA.txt">
    下载
</a>
</body>
</html>

然后就是controller了

package com.hw.controller;

import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

/**
 * @program: Maven
 * @description:
 * @author: hw
 * @create: 2019-01-04 00:22
 **/
@Controller
public class Upload {


    @RequestMapping("/upload")
    public String hello() {
        System.out.println(1);
        return "upload";
    }

    @RequestMapping("/up")
    public String save(@RequestParam("file") MultipartFile [] files,
                       HttpServletRequest request) {
        //可能为批量文件所以用数组接收
        for (MultipartFile file : files) {
            if (!file.isEmpty()) {
                String contextPath = request.getContextPath();//"/SpringMvcFileUpload"
                String servletPath = request.getServletPath();//"/up"
                String scheme = request.getScheme();//"http"
                //存放我们上传的文件路径
                String storePath = "E:\\Project\\Maven\\SpringMVC3\\src\\main\\webapp\\upload";
                //获得上传文件名
                String fileName = file.getOriginalFilename();
                File filepath = new File(storePath, fileName);
                if (!filepath.getParentFile().exists()) {
                    filepath.getParentFile().mkdirs();//如果目录不存在,创建目录
                }
                try {
                    //把文件写入目标文件地址
                    file.transferTo(new File(storePath + File.separator + fileName));
                } catch (Exception e) {

                    e.printStackTrace();
                }
            }
        }
//        返回页面
        return "index";
    }


    @RequestMapping("download")
    public ResponseEntity<byte[]> download(HttpServletRequest request, @RequestParam("filename") String filename,
                                           Model model) throws IOException {
        String downloadFilePath="E:\\Project\\Maven\\SpringMVC3\\src\\main\\webapp\\upload";//从我们的上传文件夹中去取
        File file = new File(downloadFilePath+File.separator+filename);//新建一个文件
        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.CREATED);
    }
}

点赞或者评论是我最大的动力,有问题欢迎留言或者联系q:1559810637

java 基于springMVC多图片上传,MySQL源码 @Controller @RequestMapping("/upload") public class UploadFileController { @Autowired private UploadFileService uploadFileService; @RequestMapping("/upfile") public String upload(HttpServletRequest request, @RequestParam("designation") String designation, @RequestParam("remark") String remark, //@RequestParam("file") String file, Model model)throws Exception { String str = designation; String[] st=str.split(","); //以逗号为分隔符进行截取 String re = remark; String[] stre = re.split(","); UploadFile uploadFile = new UploadFile(); //转成文件上传请求 MultipartHttpServletRequest murequest = (MultipartHttpServletRequest)request; //在文件上传请求中获取文件,根据file的name List files = murequest.getFiles("image"); if( files !=null && files.size()>0) { for(int i=0; i<files.size(); i++) { String uuid = UUID.randomUUID().toString().replace("-", "").toUpperCase()+"_"; String filename = files.get(i).getOriginalFilename(); //System.out.println("filename="+filename); int hCode =filename.hashCode(); String hex = Integer.toHexString(hCode); String mkdir = hex.charAt(0)+"\\"+hex.charAt(1)+"\\"; String path = request.getServletContext().getRealPath("/images/")+mkdir; //System.out.println("path="+path); File filepath = new File(path,filename); if(!filepath.getParentFile().exists()) { filepath.getParentFile().mkdirs(); } //将上传文件保存到目标文件中 files.get(i).transferTo(new File(path+File.separator+filename)); //获取数据库存储路径 String root = request.getContextPath(); String mkdirsql = hex.charAt(0)+"/"+hex.charAt(1)+"/"; String sqlpath = root+"/images/"+mkdirsql+filename; String imgpath = sqlpath; //图片保存到数据库的路径 uploadFile.setDesignation(st[i]); uploadFile.setRemark(stre[i]); uploadFile.setFile(filename); uploadFile.setImgpath(sqlpath); uploadFileService.addUploadFile(uploadFile); } return "success"; } return "404"; }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值