java下载远程文件直接输出到前端

有个需求是, 从别人服务器上取一张图, 直接让前端下载, 用java简单实现如下:
这是在一个servlet中的(Downloader.java):

package test;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

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

/**
 * Servlet implementation class Downloader
 */
@WebServlet("/Downloader")
public class Downloader extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public Downloader() {
        super();
    }

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

        String remoteFileUrl = "https://avatar.csdn.net/7/8/E/3_butterfly5211314.jpg";
        if (null == remoteFileUrl || remoteFileUrl.length() == 0) {
            throw new RuntimeException("remoteFileUrl is invalid!");
        }

        URL url = new URL(remoteFileUrl);

        BufferedInputStream in = null;

        // URLConnection conn = url.openConnection();
        // in = new BufferedInputStream(conn.getInputStream());

        // 这和上面两句一样的效果
        in = new BufferedInputStream(url.openStream());
        response.reset();
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition",
                "attachment;filename=\"" + URLEncoder.encode("test.jpeg", "UTF-8") + "\"");

        // 将网络输入流转换为输出流
        int i;
        while ((i = in.read()) != -1) {
            response.getOutputStream().write(i);
        }
        in.close();
        response.getOutputStream().close();
    }

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

}

测试如下:
访问:
curl -o /e/test.jpg http://localhost:8080/app/Downloader,

查看:
$ ls -l /e/test.jpg
-rw-r–r– 1 Administrator 197121 12222 三月 31 15:18 /e/test.jpg

以此记录, 欢迎补充指正!

你可能感兴趣的:(Java)