关闭

SpringMVC实现上传和下载

238人阅读 评论(0) 收藏 举报
分类:

[From] http://my.oschina.net/u/1394615/blog/311307


package com.pk.web.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

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

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;

/**
 * Created by Administrator on 2014/9/5.
 */
@Controller
@RequestMapping("file")
public class UploadController {
    @RequestMapping("/upload.do")
    public String upload(HttpServletRequest request,
            HttpServletResponse response) throws IOException {
               // 这里我用到了jar包
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());
        if (multipartResolver.isMultipart(request)) {
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;

            Iterator<String> iter = multiRequest.getFileNames();
            while (iter.hasNext()) {
                MultipartFile file = multiRequest.getFile((String) iter.next());
                if (file != null) {
                    String fileName = file.getOriginalFilename();

                    String path1 = Thread.currentThread()
                            .getContextClassLoader().getResource("").getPath()
                            + "download" + File.separator;

                    //  下面的加的日期是为了防止上传的名字一样
                    String path = path1
                            + new SimpleDateFormat("yyyyMMddHHmmss")
                                    .format(new Date()) + fileName;

                    File localFile = new File(path);

                    file.transferTo(localFile);
                }

            }

        }
        return "uploadSuccess";

    }
    @RequestMapping("/toUpload.do")
    public String toUpload() {
        return "upload";
    }

    @RequestMapping("/download")
    public String download(String fileName, HttpServletRequest request,
            HttpServletResponse response) {
        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition", "attachment;fileName="
                + fileName);
        try {
            String path = Thread.currentThread().getContextClassLoader()
                    .getResource("").getPath()
                    + "download";//这个download目录为啥建立在classes下的
            InputStream inputStream = new FileInputStream(new File(path
                    + File.separator + fileName));

            OutputStream os = response.getOutputStream();
            byte[] b = new byte[2048];
            int length;
            while ((length = inputStream.read(b)) > 0) {
                os.write(b, 0, length);
            }

             // 这里主要关闭。
            os.close();

            inputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
            //  返回值要注意,要不然就出现下面这句错误!
            //java+getOutputStream() has already been called for this response
        return null;
    }
}


还有 上传 配置文件注意

<!-- mvc注解驱动 -->

    <mvc:annotation-driven/>

    <!-- 扫描器已经有了上面这个mvc注解驱动的功能了,所有不需要了 -->

    <context:component-scan base-package="com.pk.web.controller" />



    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

        <property name="defaultEncoding" value="utf-8" />

        <property name="maxUploadSize" value="104857600"/>

        <property name="maxInMemorySize" value="4096"/>

    </bean>







    <!-- 前缀+ viewName +后缀 -->

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">

        <!-- webroot到某一指定的文件夹的路径 -->

        <property name="prefix" value="/WEB-INF/jsp/"></property>

      <!--  自己在你的 /WEB-INF/jsp下建立给jsp见面吧。或者该我上面的配置 -->

        <!-- 视图名称的后缀 -->

        <property name="suffix" value=".jsp"></property>

    </bean>

这里是html 点击下载,这里就写死了(你可以修改成你自己放的文件)。可以修改的。

  <a href="file/download.do?fileName=map.txt">下载1 </a><br />

下面这里是上传代码


   <form action="file/upload.do" method="post" enctype="multipart/form-data">

            选择文件<input type="file" name="file">

            <input type="submit" value="上传">

        </form>



web.xml 配置文件

<servlet>

        <servlet-name>springmvc</servlet-name>

        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

        <load-on-startup>1</load-on-startup>



    </servlet>



    <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>

        <init-param>

            <param-name>forceEncoding</param-name>

            <param-value>true</param-value>

        </init-param>

    </filter>



    <filter-mapping>

        <filter-name>encodingFilter</filter-name>

        <url-pattern>/*</url-pattern>

    </filter-mapping>



    <servlet-mapping>

        <servlet-name>springmvc</servlet-name>

        <!-- struts习惯使用/*,在springmvc不管用 -->

        <url-pattern>*.do</url-pattern>

    </servlet-mapping>

每个方法都返回的是一个ActionForward对象,而response是ActionForward对象参数,所以就会使response冲突! 
所以处理上传的action返回null就可以了

最终我把action里的最后 “return SUCCESS ” 改成了 “return null ”   成功了 !!!

jar 包在  oschina 这里不知道怎么上传过去给下载的。。同学们自己网上找吧! 


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:100037次
    • 积分:1490
    • 等级:
    • 排名:千里之外
    • 原创:16篇
    • 转载:193篇
    • 译文:0篇
    • 评论:10条
    文章分类
    最新评论