解决上传文件格式问题

#一 传递文件路径  
import struct
# 支持文件类型
# 用16进制字符串的目的是可以知道文件头是多少字节
# 各种文件头的长度不一样,少半2字符,长则8字符
# def typeList():
#     return {
#         "52617221": "EXT_RAR",
#         "504B0304": "EXT_ZIP"}

def typeList():
    return {
        "D0CF11E0": "DOC",
        "255044462D312E": "PDF",
        "47494638": "GIF",
        "FFD8FF": "JPG",
        "52494646": "WEBP",
        "89504E47": "PNG"}

# 字节码转16进制字符串
def bytes2hex(bytes):
    num = len(bytes)
    hexstr = u""
    for i in range(num):
        t = u"%x" % bytes[i]
        if len(t) % 2:
            hexstr += u"0"
        hexstr += t
    return hexstr.upper()


# 获取文件类型
def filetype(filename):
    binfile = open(filename, 'rb')  # 必需二制字读取
    tl = typeList()
    ftype = 'unknown'
    for hcode in tl.keys():
        numOfBytes = len(hcode) / 2  # 需要读多少字节
        binfile.seek(0)  # 每次读取都要回到文件头,不然会一直往后读取
        hbytes = struct.unpack_from("B" * numOfBytes, binfile.read(numOfBytes))  # 一个 "B"表示一个字节
        f_hcode = bytes2hex(hbytes)
        if f_hcode == hcode:
            ftype = tl[hcode]
            break
    binfile.close()
    return ftype




#二 传递文件
def typelist():
    return {
        "D0CF11E0": "DOC",
        "255044462D312E": "PDF",
        "47494638": "GIF",
        "FFD8FF": "JPG",
        "52494646": "WEBP",
        "89504E47": "PNG"}


def bytes2hex(byte):
    num = len(byte)
    hexstr = u""
    for i in range(num):
        t = u"%x" % byte[i]
        if len(t) % 2:
            hexstr += u"0"
        hexstr += t
    return hexstr.upper()


def filetype(binfile):
    tl = typelist()
    ftype = 'unknown'
    for hcode in tl.keys():
        numofbytes = len(hcode) / 2
        binfile.seek(0)
        hbytes = struct.unpack_from("B" * int(numofbytes), binfile.read(int(numofbytes)))
        f_hcode = bytes2hex(hbytes)
        if f_hcode == hcode:
            ftype = tl[hcode]
            break
    return ftype




if not filetype(upload_file) == "DOC" or filetype(upload_file) == "PDF":
    result['status'] = 400
    result['msg'] = "上传文件格式错误"
    return HttpResponse(json.dumps(result, ensure_ascii=False), content_type="application/json",
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值