SpringMvc 上传/下载 文件

1.配置 注解驱动/多部件解析器

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context = "http://www.springframework.org/schema/context"
       xmlns:is = "http://www.w3.org/2001/XMLSchema-instance"
       is:schemaLocation =
            "
            http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
            http://www.springframework.org/schema/mvc
            http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd 
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-4.2.xsd
            "
>
    <!-- scan package beans -->
    <context:component-scan base-package="com.springmvc.*">
    </context:component-scan>

    <!-- 配置 springMvc 注解驱动 -->
     <mvc:annotation-driven></mvc:annotation-driven>
     <!-- 配置 多部件 -->
    <bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver" id="multipartResolver">
        <!-- 可设置上传文件大小,上传类型,属性 等属性-->
    </bean>

</beans>

2.编写 上传/下载 的 handler 方法

package com.springmvc.handler.fileupdownload;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import org.apache.log4j.Logger;
import org.apache.log4j.spi.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class Fileupdownload {
    private static Logger rootLogger = Logger.getLogger(Fileupdownload.class);
    @RequestMapping(value="/fileUpLoad")
    public String fileUpLoad(
            @RequestParam(value="img")
            MultipartFile multipartFile,
            Model model

    ){
        //原始文件名
        String fileName=multipartFile.getOriginalFilename();
        //文件大小
        String fileSize=String.valueOf(multipartFile.getSize());
        //文件mumi 类型
        String fileContentType=multipartFile.getContentType();
        rootLogger.debug("[fileName="+fileName+",size="+fileSize+",contentType="+fileContentType+"]");
        //文件存放目标位置
        File file = new File("f:/"+fileName);
        try {
            //文件转移到目标位置
            multipartFile.transferTo(file);
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();                                   
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        model.addAttribute("fileName", fileName);
        model.addAttribute("fileSize", fileSize);
        model.addAttribute("fileContentType", fileContentType);
        return "forward:/fileupdownload/suc.jsp";
    }
    @RequestMapping(value="/fileDownLoad")
    public ResponseEntity<byte[]> fileDownLoad(){
        HttpHeaders heads=new HttpHeaders();
        try {
            String fileName = "f://11.txt";
            File file = new File(fileName);
            heads.setContentDispositionFormData("attachment",URLEncoder.encode(file.getName(), "UTF-8"));
            byte[] bytes= FileCopyUtils.copyToByteArray(file);
            ResponseEntity<byte[]> responseEntity = new ResponseEntity<byte[]>(bytes,heads,HttpStatus.CREATED);
            return responseEntity;
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;

    }
}

3.编写 submit.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>My JSP 'index.jsp' starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
  </head>

  <body>
    <form action ="<%=path %>/fileUpLoad.mvc" method="post" enctype="multipart/form-data">
        <input type = "file" name="img"></input><br/><br/>
        <a href ="<%=path %>/fileDownLoad.mvc">下载</a><br/><br/>
        <input type = "submit" ></input><br/><br/>
    </form> 
  </body>
</html>

4.编写文件上传的跳转页面 success.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>My JSP 'index.jsp' starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
  </head>

  <body>
        成功上传一个文件
        <br />
        文件名 : ${fileName }
        <br />
        文件大小 :${fileSize }&nbsp;&nbsp;bytes
        <br />
        文件mumi类型 :${ fileContentType}
        <br />
    </body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值