element ui 在线预览文本文件
文本文件
文本文件可以直接 使用 window.open(url) 来实现在线预览
文本基本都支持;我这边测了一下 txt、json、xml几种
url是请求后台的url链接,method为get;链接返回的是文件的输出流
后台大概代码长这样
public void preview(HttpServletResponse response){
File file = new File("")
response.setContentLengthLong(file.length());
String name = file.getName();
String mimeType = "";
if(StringUtils.isNotBlank(name)) {
mimeType = URLConnection.guessContentTypeFromName(name);
if(StringUtils.isBlank(mimeType)) {
mimeType = FileMimeTypeEnum.getByType(name.substring(name.lastIndexOf(".")+1)).getMimeType();
}
try {
name = URLEncoder.encode(name, "utf-8");
} catch (UnsupportedEncodingException e) {}
response.setHeader("Content-Disposition", "inline; filename=" + name);
}
response.setContentType(mimeType + "; charset=UTF-8");
try (InputStream input = new FileInputStream(file);
OutputStream output = response.getOutputStream()) {
IOUtils.copyLarge(input, output);
} catch (Exception e) {
log.error("文件下载异常!", e);
}
}
导包
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLConnection;
import java.net.URLEncoder;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.io.IOUtils;
中间获取 mimeType 有时候会为 null ;所以自己加了一个枚举类;为空就去里面再取一次
public enum FileMimeTypeEnum {
txt("txt", "text/plain"),
html("html", "text/html"),
xml("xml", "text/xml"),
json("json", "application/json"),
pdf("pdf", "application/pdf"),
jpeg("jpeg", "image/jpeg"),
jpg("jpg", "image/jpeg"),
png("png", "image/png"),
tif("tif", "image/tiff"),
tiff("tiff", "image/tiff"),
webp("webp", "image/webp"),
wbmp("wbmp", "application/octet-stream");
private String type;
private String mimeType;
private FileMimeTypeEnum(String type, String mimeType){
this.type = type;
this.mimeType = mimeType;
}
public String getType() {
return type;
}
public String getMimeType() {
return mimeType;
}
public static FileMimeTypeEnum getByType(String type) {
for(FileMimeTypeEnum venum : FileMimeTypeEnum.values()) {
if(venum.getType().equals(type)){
return venum;
}
}
return null;
}
}
图片
我这边是点击按钮触发的预览;如果是点击图片的的话就不需要写点击事件;需要注意的是 preview-src-list 属性的值是数组,类型不对的话是没有效果的
<el-button icon="el-icon-view" title="预览" @click="preview()"></el-button>
<el-image v-show="false" ref="previewImg" :src="imageSrc" :preview-src-list="previewSrcList"></el-image>
preview(){
this.previewSrcList= [url]
this.$refs.previewImg.showViewer = true;
}
参考博客:
http://blog.haoji.me/mime-type.html?from=xa
https://blog.csdn.net/m0_62209297/article/details/125208566
https://blog.csdn.net/weixin_40119412/article/details/125494017
最后
以上就是呆萌画笔最近收集整理的关于element ui在线预览文本文件 笔记的全部内容,更多相关element内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复