我下载了文件作为ajax的响应。如何从内容处置中获取文件名和文件类型并显示其缩略图。我有许多搜索结果,但找不到正确的方法。
$(".download_btn").click(function () { var uiid = $(this).data("id2"); $.ajax({ url: "http://localhost:8080/prj/" + data + "/" + uiid + "/getfile", type: "GET", error: function (jqXHR, textStatus, errorThrown) { console.log(textStatus, errorThrown); }, success: function (response, status, xhr) { var header = xhr.getResponseHeader('Content-Disposition'); console.log(header); } });
控制台输出:inline; filename=demo3.png
inline; filename=demo3.png
这是我有时使用它的方式。我假设您将附件作为服务器响应提供。
我从REST服务中这样设置响应头 response.setHeader("Content-Disposition", "attachment;filename=XYZ.csv");
response.setHeader("Content-Disposition", "attachment;filename=XYZ.csv");
function(response, status, xhr){ var filename = ""; var disposition = xhr.getResponseHeader('Content-Disposition'); if (disposition && disposition.indexOf('attachment') !== -1) { var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/; var matches = filenameRegex.exec(disposition); if (matches != null && matches[1]) { filename = matches[1].replace(/['"]/g, ''); } } }
编辑:编辑答案以适合您的问题-使用单词inline代替attachment
inline
attachment
function(response, status, xhr){ var filename = ""; var disposition = xhr.getResponseHeader('Content-Disposition'); if (disposition && disposition.indexOf('inline') !== -1) { var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/; var matches = filenameRegex.exec(disposition); if (matches != null && matches[1]) { filename = matches[1].replace(/['"]/g, ''); } } }