java 简单的word文件下载

文件下载

结合网上一些博客修改的 具体哪些太久了,记不清了

package com.cj.core.utils.download;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * @author: 刘磊
 * @Description: 文件下载
 * @date: 2019/7/5 17:19
 **/
@Slf4j
public class DownUtil {

    /**
     * 下载word
     *  urls  网址
     */
    public static String downWord(String urls, String fileName, HttpServletResponse resp) throws IOException {
        //获取文件长度
        Long nFileLength = getFileSize(urls);
        System.out.println("文件长度---->" + nFileLength);
        if (nFileLength == -1) {
            System.out.println("文件长度未知!");
            return "文件长度未知!";
        } else if (nFileLength == -2) {
            System.out.println("文件不可访问!");
            return "文件不可访问!";
        }
        //设置输出文件地址和名字
        fileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.toString());
//        fileName = new String(fileName.getBytes(), "UTF-8");
        log.info("++++++++" + fileName + "++++++++");
        resp.setCharacterEncoding("UTF-8");
        //设置响应头application/msword
        resp.setHeader("content-Type", "application/msword;charset=UTF-8");
        resp.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".docx;filename*=UTF-8''" + fileName + ".docx");
//        resp.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".docx;filename*=ISO-8859-1''" + fileName + ".docx");
//        resp.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".docx");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentLength(nFileLength.intValue());
        // 定义输出类型 msword word
        resp.setContentType("application/msword");
        OutputStream out = resp.getOutputStream();

        URL url = new URL(urls);
        HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
        httpConnection.setRequestProperty("User-Agent", "NetFox");
        String sProperty = "bytes=0-";
        httpConnection.setRequestProperty("RANGE", sProperty);
        InputStream input = httpConnection.getInputStream();
        //输出文件
        int bytes = 0;
        byte[] bufferOut = new byte[1024];
        while ((bytes = input.read(bufferOut)) != -1) {
            out.write(bufferOut, 0, bytes);
        }
        out.close();
        System.out.println("文件下载结束!");

        return "文件下载结束!";
    }

    //获得文件长度
    public static long getFileSize(String urls) {
        int nFileLength = -1;
        try {
            URL url = new URL(urls);
            HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
            httpConnection.setRequestProperty("User-Agent", "NetFox");
            int responseCode = httpConnection.getResponseCode();
            if (responseCode >= 400) {
                return -2; //-2 represent access is error
            }
            String sHeader;
            for (int i = 1; ; i++) {
                sHeader = httpConnection.getHeaderFieldKey(i);
                if (sHeader != null) {
                    if (sHeader.equals("Content-Length")) {
                        nFileLength = Integer.parseInt(httpConnection.getHeaderField(sHeader));
                        break;
                    }
                } else {
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return nFileLength;
    }
}

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java可以使用Apache POI库来生成Word文件,并且也可以使用freemarker等模板引擎来实现根据Word模板生成Word文件的功能。下面是一个简单的示例代码,可以帮助您快速入门。 首先需要引入POI和freemarker的依赖: ``` <!-- Apache POI --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.1.2</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.1.2</version> </dependency> <!-- Freemarker --> <dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.31</version> </dependency> ``` 接下来是一个简单的示例代码: ``` import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.HashMap; import java.util.Map; import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFParagraph; import org.apache.poi.xwpf.usermodel.XWPFRun; import freemarker.template.Configuration; import freemarker.template.Template; import freemarker.template.TemplateException; public class WordGenerator { public static void main(String[] args) throws IOException, TemplateException { // 读取Word模板 Configuration configuration = new Configuration(Configuration.VERSION_2_3_31); configuration.setClassForTemplateLoading(WordGenerator.class, "/"); Template template = configuration.getTemplate("template.docx"); // 准备数据 Map<String, Object> dataMap = new HashMap<String, Object>(); dataMap.put("title", "Hello, World!"); dataMap.put("content", "This is a Word document generated by Java."); // 生成Word文件 XWPFDocument document = new XWPFDocument(); XWPFParagraph paragraph = document.createParagraph(); XWPFRun run = paragraph.createRun(); Writer writer = new OutputStreamWriter(new FileOutputStream(new File("output.docx")), "UTF-8"); template.process(dataMap, writer); writer.flush(); writer.close(); } } ``` 在这个示例代码中,我们读取了名为`template.docx`的Word模板,然后准备了一些数据,利用Freemarker模板引擎将数据填充到模板中,最后生成了一个名为`output.docx`的Word文件。在实际应用中,您需要根据具体的需求修改模板和数据,并且也可以添加更多的段落、表格、图片等内容。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值