java判断文件类型
程序员文章站
2024-02-19 08:28:10
...
页面代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="${ctx}/assets/js/jquery-3.1.1.min.js"></script>
<script src="${ctx}/assets/js/layui/layui.js"></script>
<script type="text/javascript" src="${ctx}/assets/js/ajaxfileupload.js"></script>
<title>页面管理</title>
</head>
<body>
<div class="header">
<div class="logo">
<img src="${ctx}/assets/images/sso/logo.png" alt="">
</div>
</div>
<div class="main">
<h4>
<a href="${resource}">首页</a>><a>页面管理</a>
</h4>
<div class="layui-tab layui-tab-card" lay-filter="tabs">
<ul class="layui-tab-title">
<li class="layui-this"><a href="${ctx}/global/link/linkList">应用链接</a></li>
<li><a href="${ctx}/global/mien/mienList">校园风采</a></li>
</ul>
</div>
<div class="content">
<img src="${ctx}/assets/images/sso/yq_link.png" alt="">
<p><span class="add_link">创建新连接</span></p>
<div id="table" lay-filter="table">
</div>
<script type="text/html" id="barDemo">
<a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>
</div>
</div>
</div>
<div class="tc" id="tc1">
<div class="img_link">
<div class="img_left">
<img class="user_img" src="${ctx}/assets/images/sso/add_link.png" alt="">
</div>
<div class="img_right">
<span>上传图标</span>
<form id="upload_form" method="post" enctype="multipart/form-data" style='display:none;'>
<input type="file" id="img_upload" name="uploadImg" onchange="upload()" style="display:none;">
</form>
<div class="img_info">
图片格式为jpg,高400像素,宽400像素,大小不超过2M。名称、链接必填,未上传图标则显示预设图标。
</div>
</div>
<input type="hidden" id="filePath" value=""/>
<p>
<label for="nikeName">名称:</label>
<input type="text" placeholder="请输入名称" id="nickname" maxlength="8"/>
</p>
<p>
<label for="link">链接:</label>
<input type="text" placeholder="请输入链接(必须以http/https/ftp/ftps开头)" id="adress" maxlength="100"/>
</p>
</div>
</div>
<script>
function upload() {
var data = new FormData(document.getElementById("upload_form"));
$.ajax({
url: "${ctx}/global/link/uploadFile",
type: "post",
data: data,
processData: false,
contentType: false,
success: function (data) {
if(data.status>0){
layer.open({
content : data.result,
btn : [ "确定" ],
shadeClose : false,
yes : function(index) {
layer.close(index);
}
});
}else{
$(".user_img").attr("src", "${resource}"+data.src);
$("#filePath").val(data.src);
}
}
});
}
</script>
</body>
</html>
服务端Controller
public class GolbalLinkController{
//http合法链接正则表达式
private static final String REGEX_LINK = "^((ht|f)tps?):\\/\\/[\\w\\-]+(\\.[\\w\\-]+)+([\\w\\-\\.,@?^=%&:\\/~\\+#]*[\\w\\-\\@?^=%&\\/~\\+#])?$";
/**
*上传图片
*/
@Before(Tx.class)
public void uploadFile() {
UploadFile uf = getFile("uploadImg");
Integer status = 0;
try {
File file = uf.getFile();
String fileType=CheckFileTypeUtil.getFileType(file.getPath());
if(fileType.equals("jpg") || fileType.equals("png")) {
if (file.length() <= 2048000) {
String fileName = file.getName();
String type = fileName.substring(fileName.lastIndexOf("."), fileName.length());
String path = getRequest().getSession().getServletContext().getRealPath("/upload/sso");
File newFile = new File(path);
String urlname = UUID.randomUUID().toString().replaceAll("\\-", "");
urlname += type;
if (!newFile.exists()) {
newFile.mkdirs();
}
boolean b = file.renameTo(new File(path + "/" + urlname));
if (b) {
String src = "upload/sso/" + urlname;
setAttr("src", src);
}
} else {
status = 26;//上传文件大小超过限制
}
}else{
status = 25;//上传的不是文件或者格式不正确
}
} catch (Exception e) {
status = 1;
e.printStackTrace();
}
setAttr("status", status);
setAttr("result", getResult(status));
renderJson();
}
}
判断文件类型工具类
package com.guiyang.education.utils;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class CheckFileTypeUtil {
// 缓存文件头信息-文件头信息
public static final Map<String, String> mFileTypes = new HashMap<>();
static {
// images
mFileTypes.put("FFD8FF", "jpg");
mFileTypes.put("89504E47", "png");
mFileTypes.put("47494638", "gif");
mFileTypes.put("49492A00", "tif");
mFileTypes.put("424D", "bmp");
//
mFileTypes.put("41433130", "dwg"); // CAD
mFileTypes.put("38425053", "psd");
mFileTypes.put("7B5C727466", "rtf"); // 日记本
mFileTypes.put("3C3F786D6C", "xml");
mFileTypes.put("68746D6C3E", "html");
mFileTypes.put("44656C69766572792D646174653A", "eml"); // 邮件
mFileTypes.put("D0CF11E0", "doc");
mFileTypes.put("D0CF11E0", "xls");//excel2003版本文件
mFileTypes.put("5374616E64617264204A", "mdb");
mFileTypes.put("252150532D41646F6265", "ps");
mFileTypes.put("255044462D312E", "pdf");
mFileTypes.put("504B0304", "docx");
mFileTypes.put("504B0304", "xlsx");//excel2007以上版本文件
mFileTypes.put("52617221", "rar");
mFileTypes.put("57415645", "wav");
mFileTypes.put("41564920", "avi");
mFileTypes.put("2E524D46", "rm");
mFileTypes.put("000001BA", "mpg");
mFileTypes.put("000001B3", "mpg");
mFileTypes.put("6D6F6F76", "mov");
mFileTypes.put("3026B2758E66CF11", "asf");
mFileTypes.put("4D546864", "mid");
mFileTypes.put("1F8B08", "gz");
}
/**
* @param filePath 文件路径
* @return 文件头信息
* @author guoxk
* <p>
* 方法描述:根据文件路径获取文件头信息
*/
public static String getFileType(String filePath) {
return mFileTypes.get(getFileHeader(filePath));
}
/**
* @param filePath 文件路径
* @return 文件头信息
* @author guoxk
* <p>
* 方法描述:根据文件路径获取文件头信息
*/
public static String getFileHeader(String filePath) {
FileInputStream is = null;
String value = null;
try {
is = new FileInputStream(filePath);
byte[] b = new byte[4];
/*
* int read() 从此输入流中读取一个数据字节。int read(byte[] b) 从此输入流中将最多 b.length
* 个字节的数据读入一个 byte 数组中。 int read(byte[] b, int off, int len)
* 从此输入流中将最多 len 个字节的数据读入一个 byte 数组中。
*/
is.read(b, 0, b.length);
value = bytesToHexString(b);
} catch (Exception e) {
} finally {
if (null != is) {
try {
is.close();
} catch (IOException e) {
}
}
}
return value;
}
/**
* @param src 要读取文件头信息的文件的byte数组
* @return 文件头信息
* @author guoxk
* <p>
* 方法描述:将要读取文件头信息的文件的byte数组转换成string类型表示
*/
private static String bytesToHexString(byte[] src) {
StringBuilder builder = new StringBuilder();
if (src == null || src.length <= 0) {
return null;
}
String hv;
for (int i = 0; i < src.length; i++) {
// 以十六进制(基数 16)无符号整数形式返回一个整数参数的字符串表示形式,并转换为大写
hv = Integer.toHexString(src[i] & 0xFF).toUpperCase();
if (hv.length() < 2) {
builder.append(0);
}
builder.append(hv);
}
return builder.toString();
}
}
上一篇: js获取地址后面的参数
下一篇: js获取带#号链接后的参数