python图片上传和查看,可以传中文图片名字

 python图片上传和查看,可以传中文图片名字

# 图片上传
@app.route('/api/upload/', methods=['POST'])
def upload_avatar():
    basedir = os.path.abspath(os.path.dirname(__file__))
    file_dir = os.path.join(basedir, "upload")
    if not os.path.exists(file_dir):
        os.makedirs(file_dir)
    f = request.files['file']
    if f and allowed_file(f.filename):
        fname = secure_filename(f.filename)
        ext = fname.rsplit('.', 1)
        if len(ext) == 2:
            ext = ext[1]
        else:
            ext = ext[0]
        new_filename = create_uuid() + '.' + ext
        f.save(os.path.join(file_dir, new_filename))
        return jsonify({"code": 0, "msg": "上传成功",'data':new_filename})
    else:
        return jsonify({"code": 1, "msg": "上传失败"})


# 查看图片
@app.route('/img/', methods=['GET'])
def show_photo(filename):
    basedir = os.path.abspath(os.path.dirname(__file__))
    file_dir = os.path.join(basedir, "upload")
    if request.method == 'GET':
        if filename is None:
            pass
        else:
            image_data = open(os.path.join(file_dir, '%s' % filename), "rb").read()
            response = make_response(image_data)
            response.headers['Content-Type'] = 'image/png'
            return response
    else:
        pass


# 设置允许的文件格式
def allowed_file(filename):
    ALLOWED_EXTENSIONS = ['png', 'jpg', 'JPG', 'PNG', 'bmp']
    return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS

def create_uuid():  # 生成唯一的图片的名称字符串,防止图片显示时的重名问题
    import datetime,random
    nowTime = datetime.datetime.now().strftime("%Y%m%d%H%M%S");  # 生成当前时间
    randomNum = random.randint(0, 100);  # 生成的随机整数n,其中0<=n<=100
    if randomNum <= 10:
        randomNum = str(0) + str(randomNum);
    uniqueNum = str(nowTime) + str(randomNum);
    return uniqueNum;

 

你可能感兴趣的:(Python)