下载文件时如何同时返回参数

0

要在下载文件时同时传递参数给客户端,我之前想了两种方法:

  1. 使用输出流先输出返回的参数,然后换行返回文件流。
  2. 使用header返回参数。

这里我使用第二种。

Servlet代码:

package com.acgist.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.tomcat.util.http.fileupload.IOUtils;

@WebServlet(name="DownloadServlet", urlPatterns="/download")
public class DownloadServlet extends HttpServlet {
	
	private static final long serialVersionUID = 1L;

	public DownloadServlet() {
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 下载文件
		File file = new File("E:\\tmp\\1.png");
		// 头域信息
		Map<String, String> data = new HashMap<>();
		data.put("filename", "acgist.jpg");
		data.forEach((name, value) -> {
			// 设置头域
			response.setHeader(name, value);
		});
		try(FileInputStream is = new FileInputStream(file)) {
			// 输出文件
			IOUtils.copy(is, response.getOutputStream());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	}

}

Client代码:

package com.acgist.test;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.junit.Test;

public class DownloadServletTest {

	@Test
	public void download() {
		try (
			CloseableHttpClient client = HttpClients.createDefault();
			CloseableHttpResponse response = client.execute(new HttpGet("http://localhost/header4download/download"))
		) {
			Arrays.stream(response.getAllHeaders()).forEach(name -> {
				System.out.println("头域:" + name.getName() + ",值:" + name.getValue());
			});
			System.out.println("保存文件");
			IOUtils.copy(response.getEntity().getContent(), new FileOutputStream("E:\\acgist.jpg"));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
}

github地址:https://gitee.com/acgist/demo/tree/master/acgist-share/2017