注意:以下上传和下载方法未必完全正确,不同浏览器效果不同,建议不要使用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;

原文出处:http://871421448.iteye.com/blog/1564287

记录-spring MultipartFile 文件上传的更多相关文章

  1. Spring MVC 笔记 —— Spring MVC 文件上传

    文件上传 配置MultipartResolver <bean id="multipartResolver" class="org.springframework.w ...

  2. spring实现文件上传(图片解析)

    合抱之木,生于毫末,千里之行,始于足下,要想了解spring的文件上传功能,首先要知道spring是通过流的方式将文件进行解析,然后上传.那么是不是所有需要用的文件上传的地方都要写一遍文件解析器呢? ...

  3. Spring MVC文件上传教程 commons-io/commons-uploadfile

    Spring MVC文件上传教程 commons-io/commons-uploadfile 用到的依赖jar包: commons-fileupload 1.3.1 commons-io 2.4 基于 ...

  4. springboot成神之——spring的文件上传

    本文介绍spring的文件上传 目录结构 配置application DemoApplication WebConfig TestController 前端上传 本文介绍spring的文件上传 目录结 ...

  5. 【Java Web开发学习】Spring MVC文件上传

    [Java Web开发学习]Spring MVC文件上传 转载:https://www.cnblogs.com/yangchongxing/p/9290489.html 文件上传有两种实现方式,都比较 ...

  6. Spring mvc文件上传实现

    Spring mvc文件上传实现 jsp页面客户端表单编写 三个要素: 1.表单项type="file" 2.表单的提交方式:post 3.表单的enctype属性是多部分表单形式 ...

  7. Spring Boot 文件上传原理

    首先我们要知道什么是Spring Boot,这里简单说一下,Spring Boot可以看作是一个框架中的框架--->集成了各种框架,像security.jpa.data.cloud等等,它无须关 ...

  8. spring boot文件上传、下载

    主题:Spring boot 文件上传(多文件上传)[从零开始学Spring Boot]http://www.iteye.com/topic/1143595 Spring MVC实现文件下载http: ...

  9. Spring MVC文件上传出现错误:Required MultipartFile parameter 'file' is not present

    1.配置文件上传的解析器 首先需要在spring mvc的配置文件中(注意是spring mvc的配置文件而不是spring的配置文件:applicationContext.xml)配置: sprin ...

随机推荐

  1. Linux下自动监测并重启Apache服务脚本

    为了达到一个高可用的基于Apache的网站环境,在Apache由于种种原因自动停止运行之后,想立即恢复网站访问,这就需要有个工具实时监测Apache的运行状态并能够自动重启httpd服务,写了一个简单 ...

  2. log4j教程 4、配置

    上一章介绍log4j的核心组件.本章介绍如何使用配置文件来配置这些核心组件.配置log4j涉及分配级别,定义追加程序,并在配置文件中指定布局的对象. log4j.properties文件是一个键 - ...

  3. phpMyAdmin搭建及管理多台数据库服务器

    phpMyAdmin搭建及管理多台数据库服务器 环境说明: 系统版本    CentOS 6.9 x86_64         软件版本    nginx-1.12.2        php-5.5. ...

  4. 倒计时:CountDownLatch(火箭发射前的准备)读书笔记

     这是一个非常实用的多线程控制工具类,经典的场景就是 火箭发射,在火箭发射前,为了保证万无一失,往往还要进行各项设备,仪器的检查,只有等待所有的检查完毕后,引擎才能点火,      CountDown ...

  5. ReadWriteLock 读写锁(读书笔记)

     读写分离锁可以有效的帮助减少锁的竞争,提升系统的效率, 读-读不互斥 读读之间不阻塞 读-写互斥 读阻塞写,写也会阻塞读 写-写互斥 写写阻塞 在系统中,读操作次数远远大于写操作,则读写锁就可以发挥 ...

  6. 从零单排之玩转Python安全编程(II)

    转自:http://www.secpulse.com/archives/35893.html 都说Python大法好,作为一名合格的安全从业人员,不会几门脚本语言都不好意思说自己是从事安全行业的. 而 ...

  7. ionic开发之优化目录结构

    当我们来个ionic start circleApp tabs的时候,会自动生成目录结构,基本如下: 显然这不利于项目的管理,当你的项目越来越复杂的时候,这是不够的.我们必须要按照模块进行文件夹的方式 ...

  8. foreach 加& 什么意思?

    foreach 加&遍历的同时改变原数组即修改数据或者增加数据 foreach 加& 什么意思? 注意:如果我要改变数组某一个值 直接遍历的话原数组是不会变的 下面提供两种方法 1.我 ...

  9. 怎么关闭win10快速访问功能?关闭Windows10系统快速访问方法

    怎么关闭win10快速访问功能?关闭Windows10系统快速访问方法 Windows10系统的"快速访问"功能很容易泄露电脑中的隐私,用什么方法可以让这个功能消失,避免电脑的个人 ...

  10. jquery技术揭秘静态工具函数源码重构

    1.调用页面 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UT ...