[刘阳Java]_SpringMVC文件上传第1季_第10讲

今天来介绍一个关于SpringMVC框架的文件上传功能。首先我个人感觉SpringMVC框架的文件上传还是要比Struts2框架要好用一些,灵活性更强。因为SpringMVC框架的文件上传有几种不同的实现方式,所以我们先给大家介绍基于CommonsMultipartFile来实现文件上传的功能

1. 大家可以先了解案例实现的效果

 

2. 搭建一下文件上传必备的环境

  • 导入commons-fileupload-13.2.jar,commons-io-2.5.jar
  • 在SpringMVC的配置文件中增加支持文件上传的解析器如果不加入文件上传的解析,那么我们提交的请求会出现HTTP 400的错误

3. 文件上传功能需求

  • 客户端提交的上传文件需要保存到Web服务器指定的目录中
  • 服务器保存的文件名字需要进行一定的修改

4. 功能实现步骤

  • 添加支持文件上传的解析器
<?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"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    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/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <context:component-scan base-package="com.gxa.springmvc.controller"></context:component-scan>
        
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="5242880"></property>
        <property name="maxInMemorySize" value="4096"></property>
        <property name="defaultEncoding" value="UTF-8"></property>
    </bean>
    
</beans>
  • 编写文件上传的控制器代码
package com.gxa.springmvc.controller;

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

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

/**
 * SpringMVC的文件上次应用
 * @author caleb
 *
 */
@Controller
@RequestMapping("/upload")
public class FileUploadController {

    /**
     * 单个文件上传
     * @throws IOException 
     */
    @RequestMapping("/singlefileupload")
    public void singleFileUpload(@RequestParam(value="file") CommonsMultipartFile file, HttpServletRequest request, HttpServletResponse response) throws IOException {
        long start = System.currentTimeMillis();
        String uploadFileName = file.getOriginalFilename();
        String savePath = request.getServletContext().getRealPath("/") + "upload";
        savePath = savePath.replaceAll("\\\\", "/");
        String saveFileName = start + "" + uploadFileName.substring(uploadFileName.lastIndexOf("."));
        File dirs = new File(savePath);
        if (!dirs.exists()) {
            dirs.mkdirs();
        }
        file.transferTo(new File(dirs, saveFileName));
        long end = System.currentTimeMillis();
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.println("上传文件的名称 = " + uploadFileName);
        out.println("<p>");
        out.println("保存文件的路径 = " + savePath);
        out.println("<p>");
        out.println("保存文件的名称 = " + saveFileName);
        out.println("<p>");
        out.println("上传成功的时间 = " + String.valueOf(end - start) + "ms");
        out.flush();
        out.close();
    }
    
}
  • 编写文件上传的html代码,注意表单中需要加入enctype="multipart/form-data"
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="upload/singlefileupload.do" method="post" enctype="multipart/form-data">
<fieldset>
    <legend>单个文件上传</legend>
    <input type="file" name="file"><input type="submit">
</fieldset>
</form>
</body>
</html>

5. 控制器中代码解读

  • singleFileUpload中的@RequestParam("file") CommonsMultipartFile file
public void singleFileUpload(@RequestParam(value="file") CommonsMultipartFile file, HttpServletRequest request, HttpServletResponse response) throws IOException 

注意:html代码中文件上传域中的name="file"要对应Java代码中@RequestParam("file") CommonsMultipartFile file

  • file.transferTo(new File(dirs, saveFileName)); 封装了解析文件上传的IO流,同时完成将文件保存到服务器的操作
  • 因为在SpringMVC的配置文件中没有添加ViewResolver接口,所以我们就利用比较传统的Servlet API来展示上传成功的信息输出

 源码下载地址:https://pan.baidu.com/s/1eSDZwFg

转载于:https://www.cnblogs.com/liuyangjava/p/6843377.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值