`

Spring3.1 文件上传

阅读更多

注意:以下上传和下载方法未必完全正确,不同浏览器效果不同,建议不要使用IE

 

/**
  * 简单的文件上传
  * @author:qiuchen
  * @createTime:2012-6-19
  * @param request
  * @param response
  * @param errors
  * @return
  * @throws Exception
  */
 @RequestMapping(value = "/upload", method = RequestMethod.POST)
 public ModelAndView onSubmit(HttpServletRequest request,HttpServletResponse response, BindException errors) throws Exception {
  //上传文件处理器
  MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
  //文件对象
  CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile("file");
  
  //从表单域中获取文件对象的详细,如:文件名称等等
  String name = multipartRequest.getParameter("name");
  System.out.println("name: " + name);
  
  // 获得文件名(全路径)
  String realFileName = file.getOriginalFilename();
  realFileName = encodeFilename(realFileName,request);
  System.out.println("获得文件名:" + realFileName);
  // 获取当前web服务器项目路径
  String ctxPath = request.getSession().getServletContext().getRealPath("/")+ "fileupload/";
  
  // 创建文件夹
  File dirPath = new File(ctxPath);
  if (!dirPath.exists()) {
   dirPath.mkdir();
  }
  //创建文件
  File uploadFile = new File(ctxPath + realFileName);
  
  //Copy文件
  FileCopyUtils.copy(file.getBytes(), uploadFile);
  
   return new ModelAndView("success");
 }
 
/**
  * 批量上传文件
  * @author:qiuchen
  * @createTime:2012-6-19
  * @param request
  * @param response
  * @param errors
  * @return
  * @throws Exception
  */
 @RequestMapping(value = "/upload2", method = RequestMethod.POST)
 public ModelAndView onSubmit2(HttpServletRequest request,HttpServletResponse response, BindException errors) throws Exception {
  //文件处理器
  MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
  //文件列表
  Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
  //获取服务器上传文件夹地址
  String ctxPath = request.getSession().getServletContext().getRealPath("/")+ "\\" + "fileupload\\";
  //创建文件夹
  File file = new File(ctxPath);
  if (!file.exists()) {
   file.mkdir();
  }
  
  String fileName = null;
  for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
   //单个文件
   MultipartFile mf = entity.getValue();
   //文件名
   fileName = mf.getOriginalFilename();
   //创建文件
   File uploadFile = new File(ctxPath + fileName);
   //copy从内存中复制到磁盘上
   FileCopyUtils.copy(mf.getBytes(), uploadFile);
  }
    return new ModelAndView("success");
 }
 
/**  
     * 设置下载文件中文件的名称
     * @param filename  
     * @param request  
     * @return  
     */    
 public static String encodeFilename(String filename,HttpServletRequest request) {
  /**
   * 获取客户端浏览器和操作系统信息 在IE浏览器中得到的是:User-Agent=Mozilla/4.0 (compatible; MSIE
   * 6.0; Windows NT 5.1; SV1; Maxthon; Alexa Toolbar)
   * 在Firefox中得到的是:User-Agent=Mozilla/5.0 (Windows; U; Windows NT 5.1;
   * zh-CN; rv:1.7.10) Gecko/20050717 Firefox/1.0.6
   */
  String agent = request.getHeader("USER-AGENT");
  try {
   if ((agent != null) && (-1 != agent.indexOf("MSIE"))) { // IE浏览器
    String newFileName = URLEncoder.encode(filename, "UTF-8");
    newFileName = StringUtils.replace(newFileName, "+", "%20");
    if (newFileName.length() > 150) {
     newFileName = new String(filename.getBytes("GB2312"),
       "ISO8859-1");
     newFileName = StringUtils.replace(newFileName, " ", "%20");
    }
    return newFileName;
   }
   if ((agent != null) && (-1 != agent.indexOf("Mozilla"))) // 火狐浏览器
    return MimeUtility.encodeText(filename, "UTF-8", "B");
   return filename;
  } catch (Exception ex) {
   return filename;
  }
 }
 
/**
  * 文件下载
  * @author:qiuchen
  * @createTime:2012-6-19
  * @param fileName
  * @param request
  * @param response
  * @return
  * @throws Exception
  */
 @RequestMapping("/download/{fileName}")
 public ModelAndView download(@PathVariable("fileName") String fileName,HttpServletRequest request, HttpServletResponse response)throws Exception {
  request.setCharacterEncoding("UTF-8");
  
  BufferedInputStream bis = null;  //从文件中读取内容
  BufferedOutputStream bos = null; //向文件中写入内容
  
  //获得服务器上存放下载资源的地址
  String ctxPath = request.getSession().getServletContext().getRealPath("/")+ "\\" + "fileupload\\";
  //获得下载文件全路径
  String downLoadPath = ctxPath + fileName;
  System.out.println(downLoadPath);
  //如果文件不存在,退出
  File file = new File(downLoadPath);
  if(!file.exists()){
   return null;
  }
  try {
   //获得文件大小
   long fileLength = new File(downLoadPath).length();
   System.out.println(new String(fileName.getBytes("utf-8"), "ISO-8859-1"));
   response.setContentType("text/html;charset=utf-8"); //设置相应类型和编码
   response.setHeader("Content-disposition", "attachment;filename=" + new String(fileName.getBytes("utf-8"), "ISO-8859-1"));
   response.setHeader("Content-Length", String.valueOf(fileLength));
   
   bis = new BufferedInputStream(new FileInputStream(downLoadPath));
   bos = new BufferedOutputStream(response.getOutputStream());
   //定义文件读取缓冲区
   byte[] buff = new byte[2048];
   int bytesRead;
   //把下载资源写入到输出流
   while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
    bos.write(buff, 0, bytesRead);
   }
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   if (bis != null)
    bis.close();
   if (bos != null)
    bos.close();
  }
  return null;
 }
 

对于正在复制代码的你,Control+O导入命名包时,以下应该是你喜欢的:

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.BindException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;
import com.sun.xml.internal.messaging.saaj.packaging.mime.internet.MimeUtility;

 

分享到:
评论

相关推荐

    spring3.1完整包

    这个"spring3.1完整包"包含了Spring框架的多个核心模块,下面将详细介绍这些模块及其功能。 1. **org.springframework.context-3.1.0.M1.jar**:这是Spring上下文模块,提供了容器的核心功能,包括Bean的定义、配置...

    SSH 配置实例: Spring 3.1 + Hibernate 4.2 + Struts 2.3

    8. `commons-fileupload-1.2.2.jar` 支持处理HTTP请求中的文件上传。 集成SSH框架时,通常会涉及以下步骤: 1. 配置Spring的bean定义,包括DataSource、SessionFactory、HibernateTemplate或JpaTemplate,以及...

    ssh(struts2+spring2.0+hibernate3.1)上传下载例子

    在文件上传下载的例子中,Hibernate可以用来存储上传的文件信息到数据库,如文件名、大小、上传时间等,同时也可以通过查询数据库来获取文件信息以便进行下载。 文件上传通常涉及以下步骤: 1. 用户通过前端页面...

    uploadify多文件上传(java版)

    Uploadify是一款广泛使用的JavaScript库,它允许用户在网页上实现多文件上传功能。这个Java版本的实现是将Uploadify与后端服务器的Java环境相结合,为用户提供了一个高效、易用的文件上传解决方案。Uploadify的核心...

    Spring开发文档

    Spring开发文档主要涵盖Spring 3.1 MVC框架的多个方面,包括核心思想、特点、入门示例、参数传递、视图解析、拦截器、类型转换、JSON数据处理、文件上传、国际化与本地化以及JSR303验证。以下是这些知识点的详细说明...

    文件上传下载(maven + spring mvc + jetty)

    总结来说,"文件上传下载(maven + spring mvc + jetty)"项目是一个使用现代Java Web技术实现的简单示例,展示了如何利用Maven构建、Spring MVC处理HTTP请求和Jetty作为轻量级服务器。通过对这些技术的掌握,开发者...

    uploadify-v3.1 for eclipse

    《uploadify-v3.1 for eclipse:实现高效文件上传的利器》 在现代Web开发中,用户界面的交互性越来越重要,其中文件上传功能是必不可少的一环。Uploadify是一款广泛使用的JavaScript库,专为增强网页文件上传体验而...

    java文件异步上传

    当文件上传请求到达服务器时,这些方法会接收文件流,保存到服务器的磁盘上,或者将其存储到数据库或云存储服务中。处理上传的Java代码需要考虑到文件大小限制、错误处理、文件命名规则以及安全性等方面的问题。 ...

    uploadify-v3.1开发包、中文文档

    Uploadify v3.1 版本提供了更加稳定和高效的服务,特别适用于那些需要处理大量用户文件上传的Web应用。这个开发包包含了必要的文件和文档,帮助开发者快速集成并自定义上传功能。 1. **文件上传原理**:文件上传是...

    struts2.1+hibernate3.1+spring2.0项目(增删改查)

    在SSH2项目中,这可能通过Struts2的文件上传插件实现,它简化了文件上传的处理过程。 项目的结构通常包含多个子目录,如`frame`,这可能表示框架或基础结构,可能包含了项目的配置文件、实体类、DAO、Service、...

    struts2.0+spring2.0+hibernate3.1 web应用

    - 提供强大的拦截器机制,可以实现各种通用功能,如文件上传、国际化、异常处理等。 - 内置丰富的标签库,方便快速构建Web界面。 **2. Spring2.0** - **简介**: Spring框架是为了解决企业级应用开发复杂性而诞生...

    struts2+spring2.5+hibernate3.1登陆示例

    这是一个struts2+spring2.5+hibernate3.1整合登陆示例,适合于初学struts2.0的学者,数据库用的是mysql,具体的数据库文件在压缩包里,由于上传文件大小有限制,所以我把里面的lib包给删除了,读者可以自己加上去,...

    SpringMVC3.1实例源码

    SpringMVC提供了便捷的文件上传和下载支持,使用MultipartFile接口处理文件上传,通过ResponseEntity或StreamingResponseBody处理大文件下载。 9. **RESTful支持** SpringMVC 3.1加强了对RESTful风格的支持,允许...

    java文件上传和下载

    在Java后端开发中,通常使用Spring MVC框架来处理文件上传请求。 ##### 2.1 HTML表单设计 ```html ``` 表单中的`enctype`属性必须设置为`multipart/form-data`才能支持文件上传。 ##### 2.2 后端处理逻辑 ...

    Spring攻略PDF版

     3.1 在Spring IoC容器里配置Bean   3.1.1 问题描述   3.1.2 解决方案   3.1.3 实现方法   3.2 实例化Spring IoC容器   3.2.1 问题描述   3.2.2 解决方案   3.2.3 实现方法   3.3...

    Spring攻略中文版PDF

     3.1 在Spring IoC容器里配置Bean   3.1.1 问题描述   3.1.2 解决方案   3.1.3 实现方法   3.2 实例化Spring IoC容器   3.2.1 问题描述   3.2.2 解决方案   3.2.3 实现方法   3.3...

    springmvc文件上传.docx

    ### Spring MVC 文件上传详解 #### 一、Spring MVC 文件上传技术背景 在Web开发中,文件上传是一项常见的功能需求。Apache FileUpload 组件是早期Web应用中常用的文件上传解决方案之一,它提供了简单易用的API来...

Global site tag (gtag.js) - Google Analytics