基于SSM框架实现基本文件操作

一,基本说明

本文主要基于已经搭建好的SSM框架项目进行扩展,扩展的功能是文件上传,文件下载,文件批量上传。

所有的文件都可以在如下的地址进行下载:github

对于如何搭建SSM项目可以参考 SSM搭建 这个文章写得十分详细,但里面的pom.xml少了一个依赖,主要是关于jsp标签使用的,所以还需要在作者的pom.xml里加入如下的依赖项

<!--jstl引入, jsp标签库-->
<dependency>
  <groupId>jstl</groupId>
  <artifactId>jstl</artifactId>
  <version>1.2</version>
</dependency>
<dependency>
  <groupId>taglibs</groupId>
  <artifactId>standard</artifactId>
  <version>1.1.2</version>
</dependency>



二,引入依赖,修改配置

为了实现文件的操作,我们需要引入两个依赖,分别 是commons-io和commons-fileupload,引入格式可以参考maven

所以呢,在pom.xml里面加入如下的配置项

<dependency>
  <groupId>commons-fileupload</groupId>
  <artifactId>commons-fileupload</artifactId>
  <version>1.2.2</version>
</dependency>
<dependency>
  <groupId>commons-io</groupId>
  <artifactId>commons-io</artifactId>
  <version>2.4</version>
</dependency>

为了使服务器能够正常解析来自请求里面的文件内容,我们需要进行配置一个MultipartResolve的bean,为了方便这里我们贴出整个spring-mvc.xml,因为相比于原本的文件,这个文件还修改了点视图的设置,整个文件如下

<?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: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-3.0.xsd">

    <!-- 扫描web相关的bean -->
    <context:component-scan base-package="com.kevin.controller"/>

    <!-- 开启SpringMVC注解模式 -->
    <mvc:annotation-driven/>

    <!-- 静态资源默认servlet配置 -->
    <mvc:default-servlet-handler/>

    <!-- 配置jsp 显示ViewResolver -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="UTF-8" />
        <!--最大上传为31M-->
        <property name="maxUploadSize" value="32505856" />
        <property name="maxInMemorySize" value="4096"/>
    </bean>

</beans>

为了方便参数的设置,我们再加入一个配置文件value.properties,并在这个文件中定入如下的设置

directory.path = /home/kevin/tmp/file/

同时修改下我们的spring-mybatis.xml,引入这个配置文件,原本的配置文件是只引入的jdbc.properties

    <!-- 配置数据库相关参数properties的属性:${url}; 同时也引入其他的属性文件-->
    <context:property-placeholder location="classpath:*.properties"/>


三,业务代码编写

首先,直接上Controller的代码,代码如下:

package com.kevin.controller;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
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.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.List;

@Controller
@RequestMapping("/file")
public class FileController {

    @Value("${directory.path}")
    String filePath;

    @RequestMapping(value="fileUpload", method = RequestMethod.POST)
    public ResponseEntity<?> handleFileUpload(@RequestParam("file")MultipartFile file) {
        System.out.println("test fileUpload");
        if(file.isEmpty()) {
           return  ResponseEntity.status(HttpStatus.OK).body("file is empty");
        }
        try {
            String name = file.getOriginalFilename();
            File desFile = new File(filePath + name);
            FileUtils.copyInputStreamToFile(file.getInputStream(), desFile);
            return ResponseEntity.status(HttpStatus.OK).body("file upload done");
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.OK).body("file upload fail" + e.getMessage());
        }
    }

    @RequestMapping(value="fileBatchUpload", method = RequestMethod.POST)
    public ResponseEntity<?> handleFileBatchUpload(HttpServletRequest request) {
        List<MultipartFile> files = ((MultipartHttpServletRequest)request).getFiles("file");
        System.out.println(files.size());
        int size = files.size();
        try {
            MultipartFile file;
            String name;
            for (int i = 0; i < size; i++) {
                file = files.get(i);
                name = file.getOriginalFilename();
                File desFile = new File(filePath + name);
                FileUtils.copyInputStreamToFile(file.getInputStream(), desFile);
            }
            return ResponseEntity.status(HttpStatus.OK).body("file upload done");
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.OK).body("file upload fail" + e.getMessage());
        }
    }

    @RequestMapping(value="fileDownload", method = RequestMethod.POST)
    public ResponseEntity<?> handleFileDownload(@RequestParam("filename") String fileName) {
        try {
            String dfileName = new String(fileName.getBytes("gb2312"), "iso8859-1");
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", fileName);
            File file = new File(filePath + fileName);
            return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.OK).body("file download fail" + e.getMessage());

        }

    }

    @RequestMapping(value = "filePage", method = RequestMethod.GET)
    public ModelAndView handleFilePage() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("/files/filePage");
        return modelAndView;
    }

}



相应的jsp页面如下(webapp/WEB-INF/jsp/files/filePage.jsp)

<%--
  Created by IntelliJ IDEA.
  User: kevin
  Date: 17-12-16
  Time: 下午3:57
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <div>
        <span>单个文件上传</span>
        <form action="${pageContext.request.contextPath}/file/fileUpload" method="post" enctype="multipart/form-data">
            <p>选择文件: <input type="file" name="file"/></p>
            <p><input type="submit" value="提交"/></p>
        </form>
    </div>
    <hr/>
    <div>
        <span>单个文件下载</span>
        <form action="${pageContext.request.contextPath}/file/fileDownload" method="post"  target="_top" class="form form-horizontal" >
            <input type="text" class="input-text"   id="filename" name="filename" style="width:250px"  required="required">
            <input class="btn btn-primary radius" type="submit" id="submit" value="  下载  ">
        </form>
    </div>
    <hr/>
    <div>
        <span>多文件上传</span>
        <form method="POST" enctype="multipart/form-data"
              action="${pageContext.request.contextPath}/file/fileBatchUpload">
            File to upload: <input type="file" name="file"><br />
            File to upload: <input type="file" name="file"><br />
            <input type="submit" value="Upload"> Press here to upload the file!
        </form>

    </div>


</body>
</html>



到此结束,大致代码和配置就是这样了。








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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值