码迷,mamicode.com
首页 > 编程语言 > 详细

亲身实测可用的java实现wordxlsxpdf文件下载功能

时间:2020-03-24 13:02:20      阅读:77      评论:0      收藏:0      [点我收藏+]

标签:stat   nal   inline   sig   import   imp   ons   produce   tin   

本文参考原文-http://bjbsair.com/2020-03-22/tech-info/3621/
在SpringMVC的开发过程中,有时需要实现文档的下载功能。word,excel,pdf作为大家最常用的办公程序,它的文件传输就显得尤为重要,本文通过使用spring 提供的Resource封装来实现实现word/xlsx/pdf文件下载功能。话不多说。

技术图片

技术图片

package com.davidwang456;  

import java.io.File;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
import org.springframework.core.io.FileSystemResource;  
import org.springframework.core.io.Resource;  
import org.springframework.web.bind.annotation.RequestMapping;  
import org.springframework.web.bind.annotation.RequestMethod;  
import org.springframework.web.bind.annotation.ResponseBody;  
import org.springframework.web.bind.annotation.RestController;  
@RestController  
public class DownloadController {  
    private static final String APPLICATION_PDF="application/pfd";  
    private static final String APPLICATION_WORD="application/msword";  
    private static final String APPLICATION_EXCEL="application/vnd.ms-excel;charset=utf-8";   
    @RequestMapping(value="/download",method=RequestMethod.GET,produces=APPLICATION_PDF)  
    @ResponseBody  
    public Resource download(HttpServletRequest req,HttpServletResponse resp) {  
        String file);  
        File file=getFile(fileName);  
        String suffix=fileName.substring(fileName.lastIndexOf(".")+1);  
        if(suffix.equalsIgnoreCase(APPLICATION_PDF)) {  
            resp.setContentType(APPLICATION_PDF);  
            resp.setHeader("Content-Disposition", "inline;filename="+file.getName());  
        }else if(suffix.equalsIgnoreCase(APPLICATION_WORD)) {  
            resp.setContentType(APPLICATION_WORD);  
            resp.setHeader("Content-Disposition", "attachment;filename="+file.getName());  
        }else if(suffix.equalsIgnoreCase(APPLICATION_EXCEL)) {  
            resp.setContentType(APPLICATION_EXCEL);  
            resp.setHeader("Content-Disposition", "attachment;filename="+file.getName());  
        }     
        resp.setHeader("Content-Length", String.valueOf(file.length()));  
        return new FileSystemResource(file);  
    }  
    private static File getFile(String fileName) {  
        File file=new File( "path"+fileName);  
        if(!file.exists()) {  
            System.out.println("指定路径下的文件不存在!");  
        }  
        return file;  
    }  
}

亲身实测可用的java实现wordxlsxpdf文件下载功能

标签:stat   nal   inline   sig   import   imp   ons   produce   tin   

原文地址:https://blog.51cto.com/14744108/2481179

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!