HttpServletResponse附件下载详解

本文介绍了如何处理浏览器直接打开二进制附件的问题,提供了一种通过HttpServletResponse进行附件下载的解决方案,包括从第三方平台获取附件、设置附件名称和Content-Type,确保浏览器弹出下载框。文章提供相关代码示例,并附带源码下载链接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

背景

最近做了一些附件上传下载的功能,附件都是上传第三方平台,例如青云。该章记录一下附件下载。

目的

有一些浏览器在打开第三方附件下载地址的时候,会直接打开文件,看到的都是二进制乱码,而不是弹出下载框,例如火狐浏览器,该实现方式是为了兼容这种情况。

流程

第一步:前端把第三方下载地址传递给服务端,或者服务端自己从业务数据库直接获取。

第二步:前端把附件的名称传递给服务端,或者服务端自己从业务数据库直接获取,或自动生成。

第三步:通过http请求的方式获取附件的二进制流。

第四步:通过HttpServletResponse输出,浏览器会自动匹配,直接弹出下载框。

实现

备注:文章结尾有源码下载地址,下载之后,可直接用eclipse导入maven项目运行。

一)DownloadController对外接口类代码

package com.oysept.attachment.controller;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.oysept.attachment.utils.DownloadUtils;
import com.oysept.attachment.utils.HttpUtils;

/**
 * 附件下载controller
 * @author ouyangjun
 * 由于下载时返回一个流给前端,所以不能使用@RestController注解
 */
@Controller
@RequestMapping(value = "/attachment")
public class DownloadController {

    /**
     * 首页测试接口
     * 地址: http://localhost:8080/attachment/download/home
     * @return
     */
    @RequestMapping(value = "/download/home", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String home(){
        return "oysept attachment download home!";
    }
	
    /**
     * 通过第三方下载地址,获取流返回给前端
     * 原因: 有一些浏览器,直接输入第三方下载地址,会直接打开文件,不会直接下载,需要手动在浏览器配置之后才ok
     * 注意: fileUrl和fileName需要urlencode
     */
    @RequestMapping(value = "/download/urlDownload", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public void urlDownload(@RequestParam(value="fileUrl") String fileUrl,
            @RequestParam(value="fileName") String fileName, HttpServletResponse response) {
        if (StringUtils.isEmpty(fileUrl) || StringUtils.isEmpty(fileName)) {
            System.out.println("fileUrl or fileName is null!");
            return;
        }
		
        try {
            // 获取文件类型
            String fileType = fileName.substring(fileName.lastIndexOf(".")+1,fileName.length())
					.toLowerCase();
			
            // 解码
            String decodeFileUrl = URLDecoder.decode(fileUrl, "UTF-8");
            System.out.println("decodeFileUrl: " + decod
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值