`
阅读更多

spring mvc如何下载文件呢?

spring mvc怎么下载图片呢?

有两种方式:

方式一:使用注解@ResponseBody

 

@ResponseBody
	@RequestMapping(value = "/download",produces="image/jpeg")
	public byte[] downloadFile(HttpServletRequest request, HttpServletResponse response,String contentType2,boolean isInline)
			throws IOException {
		byte[]bytes=FileUtils.getBytes4File("D:\\Temp\\cc.jpg");
//		response.addHeader("Content-Disposition", downloadType+";filename=\"a.jpg\"");
		WebServletUtil.setDownloadContentDisposition(isInline, "c.jpg", response);
		return bytes;

	}

 WebServletUtil.setDownloadContentDisposition 的实现如下:

 

 

/***
	 * spring MVC下载文件设置的Content-Disposition
	 * @param isInline
	 * @param fileName
	 * @return
	 */
	public static String getContentDisposition(boolean isInline,String fileName){
		String downloadType=null;
		if(isInline){
			downloadType=Constant2.CONTENT_DISPOSITION_INLINE;
		}else{
			downloadType=Constant2.CONTENT_DISPOSITION_ATTACHMENT;
		}
		if(ValueWidget.isNullOrEmpty(fileName)){
			fileName="name_not_specified";
		}
		String format=downloadType+";filename=\""+fileName+"\"";
		return format;
	}
	/***
	 * 下载文件(或内联显示)时设置Content-Disposition
	 * @param isInline
	 * @param fileName
	 * @param response
	 */
	public static void setDownloadContentDisposition(boolean isInline,String fileName, HttpServletResponse response){
		response.addHeader(Constant2.CONTENT_DISPOSITION, WebServletUtil.getContentDisposition(isInline, fileName));
	}

 注意:(1)一定要通过@RequestMapping注解的produces 设置response 的content type;

(2)设置应答头时要使用addHeader,而不是setHeader

 

方式二:使用ResponseEntity

@RequestMapping(value = "/download3")
    public ResponseEntity<byte[]> download() throws IOException {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.IMAGE_JPEG);
//        headers.setContentDispositionFormData("inline", "dict.jpg");//attachment
        headers.set(Constant2.CONTENT_DISPOSITION,WebServletUtil.getContentDisposition(true, "dict.jpg"));
        return new ResponseEntity<byte[]>(FileUtils.getBytes4File("D:\\Temp\\cc.jpg"),
                                          headers, HttpStatus.CREATED);
    }

/***
	 * favicon.ico 
	 * @throws IOException 
	 */
	@RequestMapping(value = "/favicon.ico")
	public ResponseEntity<byte[]> faviconIco(HttpServletRequest request) throws IOException {
		HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.IMAGE_PNG);
        String faviconIcoName="sms-4.ico";
        headers.set(Constant2.CONTENT_DISPOSITION,WebServletUtil.getContentDisposition(true, faviconIcoName));
        ///home/whuang/software/apache-tomcat-7.0.53/webapps/ROOT/
        String webappPath=null;
        if(WebServletUtil.isLocalIp(request)){//服务器在本机(访问ip为127或localhost)
        	webappPath=WebServletUtil.getRealPath(request);
        }else{
        	webappPath=DictionaryParam.get(Constant2.DICTIONARY_GROUP_GLOBAL_SETTING, "WEB-INF_LOC");
        }
        return new ResponseEntity<byte[]>(FileUtils.getBytes4File(
        		webappPath
        		+"WEB-INF/static/img/"+faviconIcoName),
                                          headers, HttpStatus.CREATED);

	}

  

注意:不要使用headers.setContentDispositionFormData 来设置Content-Disposition

分享到:
评论
4 楼 chen_lian 2016-02-18  
HttpStatus.CREATED 改为HttpStatus.OK 否则IE下面不好用
3 楼 chen_lian 2016-02-18  
楼主我给补充了一下 嘿嘿
2 楼 chen_lian 2016-02-18  
public class FileUtil {

	/**
	 * 读取二进制文件并且写入数组里
	 * @param filePath
	 * @return
	 * @throws IOException 
	 * @throws FileNotFoundException 
	 */
	public static byte[] getBytes4File(String filePath) throws IOException {

		InputStream in = null;
		BufferedInputStream buffer = null;
		DataInputStream dataIn = null;
		ByteArrayOutputStream bos = null;
		DataOutputStream dos = null;
		byte[] bArray = null;
		try {
			in = new FileInputStream(filePath);
			buffer = new BufferedInputStream(in);
			dataIn = new DataInputStream(buffer);
			bos = new ByteArrayOutputStream();
			dos = new DataOutputStream(bos);
			byte[] buf = new byte[1024];
			while (true) {
				int len = dataIn.read(buf);
				if (len < 0)
					break;
				dos.write(buf, 0, len);
			}
			bArray = bos.toByteArray();

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;

		} finally {

			if (in != null)
				in.close();
			if (dataIn != null)
				dataIn.close();
			if (buffer != null)
				buffer.close();
			if (bos != null)
				bos.close();
			if (dos != null)
				dos.close();
		}

		return bArray;
	}
}





1 楼 chen_lian 2016-02-18  
FileUtils 这个类没有源码

相关推荐

    spring mvc 官方文档

    本文详细介绍spring MVC的原理和开发心得体会。

    精通Spring MVC 4

    本书共计10章,分别介绍了快速搭建Spring Web应用、精通MVC结构、URL映射、文件上传与错误处理、创建Restful应用、保护应用、单元测试与验收测试、优化请求、将Web应用部署到云等内容,循序渐进地讲解了Spring MVC4...

    Spring MVC 文件上传下载 后端 - Java.zip

    Spring MVC 文件上传下载 后端 - Java.zip

    Spring mvc 教程

    很有用的Spring mvc中文文档

    Spring MVC 入门实例

    在 Spring MVC 中, jsp 文件中尽量不要有 Java 代码, 只有 HTML 代码和"迭代(forEach)"与"判断(if)"两个jstl标签. jsp 文件只作为渲染(或称为视图 View)模板使用. 好了, 我们开始吧. 首先我们需要一个放在 WEB-INF...

    spring MVC .docx

    spring MVC .docx 文档

    spring mvc框架依赖全面jar

    spring mvc轻量级框架搭建,依赖全面jar文件包。下载解压直接将jar文件复制到工程中的lib中。

    spring mvc文件上传实现进度条

    spring mvc文件上传,通过监听器实现进度条

    [免费]Spring MVC学习指南(高清)

    全书共计12章,分别从Spring框架、模型2和MVC模式、Spring MVC介绍、控制器、数据绑定和表单标签库、传唤器和格式化、验证器、表达式语言、JSTL、国际化、上传文件、下载文件多个角度介绍了Spring MVC。除此之外,...

    spring MVC 配置文档

    DispatcherServlet 是Spring MVC 的入口 所有进入Spring Web 的 Request 都经过 DispatcherServlet 需要在 web.xml 中注册 DispatcherServlet &lt;servlet&gt; &lt;servlet-name&gt;dispatherContext&lt;/servlet-name&gt; ...

    SpringMVCDemo:Spring MVC 框架知识案例

    8.Spring MVC 下载 Excel 文档的需求案例 9.Spring MVC RESTful 风格的请求方式案例 10.Spring + Spring MVC + JDBCTemplate 整合并通过 RESTful 风格获取所有用户信息案例 11.Spring MVC 数据绑定案例 12.Spring ...

    大优惠 Spring MVC学习指南(第2版)2017.pdf

    全书共计12章,分别从Spring框架、模型2和MVC模式、Spring MVC介绍、控制器、数据绑定和表单标签库、传唤器和格式化、验证器、表达式语言、JSTL、国际化、上传文件、下载文件多个角度介绍了Spring MVC。除此之外,...

    spring mvc上传 下载ftp文件

    spring mvc上传 下载ftp文件

    Spring MVC+MyBatis开发从入门到项目实战

    第2篇是MyBatis技术入门,包括剖析JDBC的弊端、MyBatis的背景介绍、入门程序的编写、配置文件的剖析、高级映射及缓存结构的讲解,最后还介绍了MyBatis与Spring框架的整合。第3篇是Spring MVC技术入门,包括Spring ...

    Spring MVC入门教程

    七、spring mvc 如何访问到静态的文件,如jpg,js,css? 八、spring mvc 请求如何映射到具体的Action中的方法? 九、spring mvc 中的拦截器: 十、spring mvc 如何使用拦截器? 十一、spring mvc 如何实现全局的异常...

    Spring MVC 4.2.4.RELEASE 中文文档v

    Spring MVC 4.2.4.RELEASE 中文文档Spring MVC 4.2.4.RELEASE 中文文档

    Spring MVC 教程 快速入门 深入分析

    七、spring mvc 如何访问到静态的文件,如jpg,js,css? 八、spring mvc 请求如何映射到具体的Action中的方法? 九、spring mvc 中的拦截器: 十、spring mvc 如何使用拦截器? 十一、spring mvc 如何实现全局的异常...

    SSM(spring+spring MVC+mybatis)开发学生信息后台管理系统

    SSM(spring+spring MVC+mybatis)开发学生信息后台管理系统,实现学生增删改查功能设计一个简单的学生信息管理系统,要求使用SSM框架技术整合实现,用户登录后能够通过Web页面添加、删除、修改和查询学生信息 ...

Global site tag (gtag.js) - Google Analytics