JAVA开发Spring MVC实现文件上传

7 篇文章 0 订阅
2 篇文章 0 订阅

在spring mvc中实现文件上传的大致步骤如下:
一,pox.xml配置中添加依赖,

<dependency>
  <groupId>commons-fileupload</groupId>
  <artifactId>commons-fileupload</artifactId>
  <version>1.3.1</version>
</dependency>

二,在resources中配置新建spring-mvc.xml文件:

 <?xml version="1.0" encoding="UTF-8"?>
 <!--suppress SpringXmlModelInspection -->
 <beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:context="http://www.springframework.org/schema/context"
   xmlns:tx="http://www.springframework.org/schema/tx"
   xmlns:aop="http://www.springframework.org/schema/aop"
   xmlns:mvc="http://www.springframework.org/schema/mvc"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   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
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc.xsd">

<!--suppress SpringXmlModelInspection -->
<!--开启注解-->
<context:component-scan base-package="com.k9501.controller"/>
<!--开启适配器和处理器的注解-->
<mvc:annotation-driven/>
<!--视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <!--前缀和后缀-->
    <property name="prefix" value="/jsp/"/>
    <property name="suffix" value=".jsp"/>
</bean>

<!--文件上传配置-->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <!--设置字符集-->
    <property name="defaultEncoding" value="UTF-8"/>
    <!--设置文件上传大小-->
    <property name="maxUploadSizePerFile" value="5242880"/>
    <!--设置总大小-->
    <property name="maxUploadSize" value="47185920"/>
</bean>
</beans>

三,页面jsp
在webapp文件夹下,新建upload.jsp文件

 <%--
 Created by IntelliJ IDEA.
 User: Administrator
 Date: 2019/6/4
 Time: 15:43
 To change this template use File | Settings | File Templates
 --%>
 <%@ page contentType="text/html;charset=UTF-8" language="java" %>

<html>
 
 <head>
<title>文件上传</title>
</head>
<body>
单个文件上传
<form action="${pageContext.request.contextPath}/upload.action" method="post" enctype="multipart/form-data">
头像:<input type="file" name="imgName"> <input type="submit">

 </form>
<hr/>
多文件上传
<form action="${pageContext.request.contextPath}/uploadMany.action" method="post" enctype="multipart/form-data">
头像:<input type="file" multiple="multiple" name="fileMany"> <input type="submit">

</form>
<hr/>
多文件上传,分包处理
<form action="${pageContext.request.contextPath}/uploadManyPage.action" method="post" enctype="multipart/form-data">
头像:<input type="file" multiple="multiple" name="fileManyPage"> <input type="submit">

</form>
<hr/>
多文件上传,分包处理工具类
<form action="${pageContext.request.contextPath}/uploadManyPageUtil.action" method="post" enctype="multipart/form-data">
头像:<input type="file" multiple="multiple" name="fileName"> <input type="submit">

</form>
</body>
</html>

四,写控制器
(导包省略)

  @Controller
 public class UploadController {
//上传单个文件
@RequestMapping(value = "/upload.action",produces = "application/json;charset=utf-8")
@ResponseBody
public String upload(MultipartFile imgName){
    String originalFilename = imgName.getOriginalFilename();

    try {
        imgName.transferTo(new File("E:\\study\\images",originalFilename));
        return "success";
    } catch (IOException e) {
        e.printStackTrace();
        return "error";
    }
}

//多文件
@RequestMapping(value = "/uploadMany.action",produces = "application/json;charset=utf-8")
@ResponseBody
public String uploadMany(MultipartRequest request){
    List<MultipartFile> multipartFileList = request.getFiles("fileMany");
    try {
       for (int i=0;multipartFileList!=null&&i<multipartFileList.size();i++) {

            MultipartFile multipartFile = multipartFileList.get(i);

            String originalFilename = multipartFile.getOriginalFilename();

            multipartFile.transferTo(new File("E:\\study\\images", originalFilename));
       }
            return "success";

        } catch (IOException e) {
            e.printStackTrace();
        return "error";
        }
    }

//多包处理,
@RequestMapping(value = "/uploadManyPage.action",produces = "application/json;charset=utf-8")
@ResponseBody
public String uploadManyPage(MultipartRequest request){
    // 路径如  e:/images/2019/06/04/16/51/35/UUID.jpg
    List<MultipartFile> multipartFileList = request.getFiles("fileManyPage");
    try {
    for (int i=0;multipartFileList!=null&&i<multipartFileList.size();i++) {
        MultipartFile multipartFile = multipartFileList.get(i);
        //获取图片名称
        String originalFilename = multipartFile.getOriginalFilename();
        //获取文件类型、
        String lastPath = originalFilename.substring(originalFilename.lastIndexOf("."));
        //uuid
        String uuidPath = UUID.randomUUID().toString();
        //获取日期包
        String datePath = new SimpleDateFormat("yyyy\\MM\\dd\\HH\\mm\\ss").format(new Date());
        //完成路径
        File file = new File("e:\\study\\images", datePath);
        //判断文件夹是否存在
        if (!file.exists()){
            file.mkdirs();
        }
        String endPath="E:\\study\\images\\"+datePath+"\\"+uuidPath+lastPath;
        System.out.println("endPath = " + endPath);
        multipartFile.transferTo(new File(endPath));
       }
        return "success";
        } catch (IOException e) {
            e.printStackTrace();
        return "error";
        }
    }

//多包处理, 工具类
@RequestMapping(value = "/uploadManyPageUtil.action",produces = "application/json;charset=utf-8")
@ResponseBody
public String uploadManyPageUtil(MultipartRequest request){
    FileUploadUtil.fileUploadUtil(request,"fileName","e:\\study\\images\\");

    return "success";
}
}

另外多包处理util工具类参考:

 public class FileUploadUtil {
public static Map<String,Object> fileUploadUtil(MultipartRequest request,String fileName,String targetPage){
// 路径如  e:/images/2019/06/04/16/51/35/UUID.jpg
    List<MultipartFile> multipartFileList = request.getFiles("fileName");
    try {
        for (int i=0;multipartFileList!=null&&i<multipartFileList.size();i++) {
            MultipartFile multipartFile = multipartFileList.get(i);
            //获取图片名称
            String originalFilename = multipartFile.getOriginalFilename();
            //获取文件类型、
            String lastPath = originalFilename.substring(originalFilename.lastIndexOf("."));
            //uuid
            String uuidPath = UUID.randomUUID().toString();
            //获取日期包
            String datePath = new SimpleDateFormat("yyyy\\MM\\dd\\HH\\mm\\ss").format(new Date());
            //完成路径
            File file = new File(targetPage, datePath);
            //判断文件夹是否存在
            if (!file.exists()){
                file.mkdirs();
            }
            String endPath=targetPage+datePath+"\\"+uuidPath+lastPath;

            multipartFile.transferTo(new File(endPath));
        }
        return null;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

杰少2020

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值