当前位置: 代码网 > it编程>编程语言>Java > 前端发送的请求Spring如何返回一个文件详解

前端发送的请求Spring如何返回一个文件详解

2024年09月04日 Java 我要评论
前言因为本人主要是学习后端java的,前端呢只是了解一点点基础语法,所以本篇文章中可能会显得有一些不专业,所以呢,请大家多多包涵。对于前后端交互的部分,我使用的最多的就是通过 ajax 来像后端发送

前言

因为本人主要是学习后端java的,前端呢只是了解一点点基础语法,所以本篇文章中可能会显得有一些不专业,所以呢,请大家多多包涵。

对于前后端交互的部分,我使用的最多的就是通过 ajax 来像后端发送 http 请求,但是呢,众所周知,ajax 默认是不直接支持文件的下载的(即,它不能直接触发浏览器的下载管理器),,你通常需要将文件内容作为某种形式的数据(如base64编码的字符串或blob)返回,并在前端处理这些数据以触发下载或显示文件内容。

那么这篇文章,我将介绍如何对后端即将传输的文件做处理,以至于我们的前端能够得到这个文件。

如果文件可以通过url访问

如果我们要上传的问价可以通过 url 访问的话,那么我们就可以使用 urlresource 来对文件进行处理:

import org.springframework.core.io.resource;  
import org.springframework.core.io.urlresource;  
import org.springframework.http.httpheaders;  
import org.springframework.http.mediatype;  
import org.springframework.http.responseentity;  
import org.springframework.web.bind.annotation.getmapping;  
import org.springframework.web.bind.annotation.requestparam;  
import org.springframework.web.bind.annotation.restcontroller;  
 
import java.net.malformedurlexception;  
import java.nio.file.paths;  
 
@restcontroller  
public class filedownloadcontroller {  
 
    @getmapping("/download")  
    public responseentity<resource> downloadfile(@requestparam string filename) throws malformedurlexception {  
        // 假设文件存储在服务器上的某个目录  
        string filepath = "/path/to/your/files/" + filename;  
        resource file = new urlresource(filepath);  
 
        if (file.exists() || file.isreadable()) {  
            // 设置http头以支持文件下载  
            httpheaders headers = new httpheaders();  
            headers.add(httpheaders.content_disposition, "attachment; filename=\"" + file.getfilename() + "\"");  
            headers.add(httpheaders.cache_control, "no-cache, no-store, must-revalidate");  
            headers.add(httpheaders.pragma, "no-cache");  
            headers.add(httpheaders.expires, "0");  
 
            return responseentity.ok()  
                    .headers(headers)  
                    .contenttype(mediatype.application_octet_stream)  
                    .body(file);  
        } else {  
            // 处理文件不存在或不可读的情况  
            return responseentity.notfound().build();  
        }  
    }  
}
  • 设置了content-disposition为attachment,这通常用于提示浏览器将响应作为文件下载。但是,如果你希望图片直接在浏览器中显示,可能不需要这个设置。
  • cache_control 这个请求头就是缓存控制
  • expires 过期时间

注意我们这个类的返回类型需是 responseentity<>,该类用于构建 http 响应。响应中的 contenttype 用来设置我们返回的 body 是什么类型,mediatype 类中有很多的静态类型:

public class mediatype extends mimetype implements serializable {
    private static final long serialversionuid = 2069937152339670231l;
    public static final mediatype all = new mediatype("*", "*");
    public static final string all_value = "*/*";
    public static final mediatype application_atom_xml = new mediatype("application", "atom+xml");
    public static final string application_atom_xml_value = "application/atom+xml";
    public static final mediatype application_cbor = new mediatype("application", "cbor");
    public static final string application_cbor_value = "application/cbor";
    public static final mediatype application_form_urlencoded = new mediatype("application", "x-www-form-urlencoded");
    public static final string application_form_urlencoded_value = "application/x-www-form-urlencoded";
    public static final mediatype application_graphql = new mediatype("application", "graphql+json");
    public static final string application_graphql_value = "application/graphql+json";
    public static final mediatype application_json = new mediatype("application", "json");
    public static final string application_json_value = "application/json";
    /** @deprecated */
    @deprecated
    public static final mediatype application_json_utf8;
    /** @deprecated */
    @deprecated
    public static final string application_json_utf8_value = "application/json;charset=utf-8";
    public static final mediatype application_octet_stream;
    public static final string application_octet_stream_value = "application/octet-stream";
    public static final mediatype application_pdf;
    public static final string application_pdf_value = "application/pdf";
    public static final mediatype application_problem_json;
    public static final string application_problem_json_value = "application/problem+json";
    /** @deprecated */
    @deprecated
    public static final mediatype application_problem_json_utf8;
    /** @deprecated */
    @deprecated
    public static final string application_problem_json_utf8_value = "application/problem+json;charset=utf-8";
    public static final mediatype application_problem_xml;
    public static final string application_problem_xml_value = "application/problem+xml";
    public static final mediatype application_rss_xml;
    public static final string application_rss_xml_value = "application/rss+xml";
    public static final mediatype application_ndjson;
    public static final string application_ndjson_value = "application/x-ndjson";
    /** @deprecated */
    @deprecated
    public static final mediatype application_stream_json;
    /** @deprecated */
    @deprecated
    public static final string application_stream_json_value = "application/stream+json";
    public static final mediatype application_xhtml_xml;
    public static final string application_xhtml_xml_value = "application/xhtml+xml";
    public static final mediatype application_xml;
    public static final string application_xml_value = "application/xml";
    public static final mediatype image_gif;
    public static final string image_gif_value = "image/gif";
    public static final mediatype image_jpeg;
    public static final string image_jpeg_value = "image/jpeg";
    public static final mediatype image_png;
    public static final string image_png_value = "image/png";
    public static final mediatype multipart_form_data;
    public static final string multipart_form_data_value = "multipart/form-data";
    public static final mediatype multipart_mixed;
    public static final string multipart_mixed_value = "multipart/mixed";
    public static final mediatype multipart_related;
    public static final string multipart_related_value = "multipart/related";
    public static final mediatype text_event_stream;
    public static final string text_event_stream_value = "text/event-stream";
    public static final mediatype text_html;
    public static final string text_html_value = "text/html";
    public static final mediatype text_markdown;
    public static final string text_markdown_value = "text/markdown";
    public static final mediatype text_plain;
    public static final string text_plain_value = "text/plain";
    public static final mediatype text_xml;
    public static final string text_xml_value = "text/xml";
    private static final string param_quality_factor = "q";
}

大家可以根据自己要返回的文件的具体类型来选择。

后端对文件进行处理了之后,前端也是需要做出调整的,由于 ajax 默认不支持文件的下载,所以我们选择使用 fetch 来作为 web api。

什么是fetch

这里的解释来自于百度:

fetch 是 web api 的一部分,它提供了一种简单、逻辑清晰的方式来跨网络异步获取资源(包括文件、网络请求等)。fetch api 返回一个 promise,这个 promise 解析为一个 response 对象,该对象包含来自服务器的各种响应信息,比如响应头、状态码等,并且允许你访问响应体(response body)的内容。

与 xmlhttprequest 相比,fetch 提供了一个更现代、更简洁的api来访问和操作网络请求和响应。fetch 支持 promise api,这使得异步逻辑更加容易编写和理解。

fetch 处理文件更加的方便,所以这里我们选择使用 fetch。

function downloadfile(url, filename) {  
    fetch(url, {  
        method: 'post', 
        // 可以添加其他必要的请求头,如认证信息等  
        headers: {  
            // 示例:'authorization': 'bearer your_token_here'  
        },  
        // 告诉浏览器我们期望的响应类型是一个blob  
        responsetype: 'blob'  
    })  
    .then(response => {  
        // 检查响应是否成功  
        if (!response.ok) {  
            throw new error('network response was not ok');  
        }  
        // 返回blob对象  
        return response.blob();  
    })  
    .then(blob => {  
        // 创建一个指向该blob的url  
        // 我们可以通过这个生成的url访问到这个文件
        const url = window.url.createobjecturl(blob); 
  
  		// 我这里就直接将图片的url给用了
        let pic = document.queryselector('.main .left .user .picture')
        pic.style.backgroundimage = 'url(' + url + ')' 
  
  		// 这个用于将生成的url给清除掉,我们这里可以先不清,
  		//如果清除了的话,前端可能无法通过这个url获取到这个文件,
  		//我们可以在关闭页面的时候调用这个方法
        // 清理工作  
        // window.url.revokeobjecturl(url);  
    })  
    .catch(error => {  
        console.error('there has been a problem with your fetch operation:', error);  
    });  
} 

如果文件无法通过url访问到

如果文件不是通过url访问到的,例如它们存储在文件系统中的话,就需要依靠 filesystemresource 等其他资源类。

@requestmapping("/getuserpic")
public responseentity<resource> getuserpic(string filename) {
    //获取到存储在文件系统中的文件
    resource resource = new filesystemresource(constant.path + filename);
    return responseentity.ok()
            .contenttype(mediatype.image_jpeg)
            .header(httpheaders.content_disposition,"attachment; filename=" + resource.getfilename())
            .body(resource);}

然后前端呢就还是通过 fetch 来为文件创建一个指向该文件的url,就可以通过这个url访问了。

如果使用了aop对返回结果做了处理

如果我们的spring使用了aop来对返回结果进行了统一处理的话,对于返回的 responseentity<> 我们还需要做出调整:

@controlleradvice
public class responseadvice implements responsebodyadvice {
    @autowired
    private objectmapper objectmapper;
    @override
    public boolean supports(methodparameter returntype, class convertertype) {
        return true;
    }

    @override
    public object beforebodywrite(object body, methodparameter returntype, mediatype selectedcontenttype, class selectedconvertertype, serverhttprequest request, serverhttpresponse response) {
    	//调整在这里,如果返回的类型是resource的时候就直接返回
        if (body instanceof resource) {
            return body;
        }
        if (body instanceof string) {
            try {
                return objectmapper.writevalueasstring(body);
            } catch (jsonprocessingexception e) {
                throw new runtimeexception(e);
            }
        }else if (body instanceof result) {
            return body;
        }else {
            return result.success(body);
        }
    }
}

总结 

到此这篇关于前端发送的请求spring如何返回一个文件的文章就介绍到这了,更多相关前端发送请求spring返回文件内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com