SpringMVC上传下载.

来源:互联网 发布:最稳定的域名申请 编辑:程序博客网 时间:2024/06/08 08:01

一、导入jar


二、配置

      1.web.xml配置

        <servlet>
           <servlet-name>spring</servlet-name>
           <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
           <!-- <init-param>
               <param-name>contextConfigLocation : String</param-name>
               <param-value>classpath:/WEB-INF/spring-servlet.xml</param-value>
           </init-param> -->
           <load-on-startup>1</load-on-startup>
   </servlet>
    <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

      2.spring-servlet.xml配置(注意:springmvc默认加载WEB-INF下面的servlet name-servlet.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:p="http://www.springframework.org/schema/p"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd   
            http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd   
            http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd   
            http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.0.xsd">

<context:component-scan base-package="cn.com.controller"/>
<mvc:annotation-driven/>

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="defaultEncoding" value="utf-8"/>
</bean>

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/pages/"/>
    <property name="suffix" value=".jsp"></property>
</bean>
</beans>

三、页面

index.jsp

<body>
<a href="${pageContext.request.contextPath }/mvc/toUpload"> Upload </a>
<a href="${pageContext.request.contextPath }/mvc/toDownload">Download</a>
</body>

upload.jsp

<body>

<h1>${message }</h1>
    <form action="${pageContext.request.contextPath }/mvc/upload" enctype="multipart/form-data" method="post">
        File:<input type="file" name="uploadFile" onchange="getFileSize(this);"/><br/>
        <input type="submit" value="Submit"/><br/>
    </form>

</body>

<script type="text/javascript">
  function getFileSize(fileid) {
    try {
     var fileSize = 0;
     //IE浏览器
     if ($.support.msie) {
        
         var objFSO = new ActiveXObject("Scripting.FileSystemObject");
         var filePath = $(fileid)[0].value;
         var objFile = objFSO.getFile(filePath);
         var fileSize = objFile.size;
         fileSize = fileSize / 1048576;

    }
 //其他浏览器
    else {
     fileSize = $(fileid)[0].files[0].size
     fileSize = fileSize / 1048576;
    
    }
    if(fileSize>10){
        alert("上传文件不能大于10M");
    }
    }
    catch (e) {
    alert("Error is :" + e);
    }
}

</script>


download.jsp

<body>
<a href="${pageContext.request.contextPath }/mvc/download?fileName=jar.png">jar.png</a><br/>
<a href="${pageContext.request.contextPath }/mvc/download?fileName=development.zip">development.zip</a>
</body>


四、上传下载文件class

    package cn.com.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;

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

import org.springframework.stereotype.Controller;
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;

import com.domain.User;

@RequestMapping("/mvc")
@Controller("fileUploadController")
public class FileUploadController {
    @RequestMapping("toUpload")
    public String toUploadPage(HttpServletRequest request){
        request.setAttribute("message", "please upload a image");
        return "upload";
    }
    @RequestMapping("upload")
    public String upload(User user,HttpServletRequest request, @RequestParam(value="uploadFile") MultipartFile file) throws Exception{
        //MultipartFile封装了上传文件的所有信息
        //获取上传的源文件的名称
        if(file.isEmpty()){
            System.out.println("请选择要上传的文件...");
            return "error";
        }
        String fileName = file.getOriginalFilename();
        String realpath = request.getSession().getServletContext().getRealPath("/upload");
        File f = new File(realpath+"\\"+fileName);
        FileCopyUtils.copy(file.getInputStream(), new FileOutputStream(f));
        return "success";
    }
    @RequestMapping("download")
    public String download(String fileName,HttpServletRequest request,HttpServletResponse response) throws Exception{
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        String path = request.getSession().getServletContext().getRealPath("/upload")+"/"+fileName;
        response.setHeader("Content-disposition", "attachment;filename="+new String(fileName.getBytes("iso8859-1"),"utf-8"));
//        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(new File(path)));
//        BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
//        byte[] b = new byte[2048];
//        int len;
//        while((len=bis.read(b,0,b.length))!=-1){
//            bos.write(b, 0, len);
//        }
//        bis.close();
//        bos.close();
        FileCopyUtils.copy(new FileInputStream(new File(path)), response.getOutputStream());
        return null;
    }
    @RequestMapping("toDownload")
    public String toDowmload(){
        return "download";
    }
}


注:@RequestParam(value="uploadFile"),此注解value的值必须与表单中上传文件的name属性值相同,download方法中的两种方式都可以实现具体功能:注释掉的code是一种方式,FileCopyUtils是一种方式。实际上,文件名,文件路径这些信息应该保存在数据库中,但是本文中只用到了springmvc,没有使用其他持久化框架或者jdbc,没有与数据库交互,所以有些本来需要向数据库中保存或者提取的数据,写死或者给省略掉了。后续会进行更改。

0 0
原创粉丝点击