django文件上传下载API

from django.shortcuts import render
from django.http import HttpResponse, FileResponse
from django.core.files.storage import get_storage_class
from django.core.files.base import ContentFile
from django_api import settings
import time, datetime
from . import models

# Create your views here.


def upload_file(request):  # curl -F "file=@anaconda-ks.cfg" "http://192.168.0.110:8000/newcct/upload/"
    """curl 上传文件"""
    try:
        file_object = request.FILES.get('file', '')  # 获取文件
        print('file name: ' + file_object.name)
        print('file size: ' + str(file_object.size))
        print('file content_type: ' + file_object.content_type)
        print(type(file_object))
        timestamp = file_object.name.split('_')[2].split('.')[0]
        date_array = datetime.datetime.fromtimestamp(int(timestamp)).strftime("%Y-%m-%d %H:%M:%S")
        print(timestamp)
        print(date_array)
        if file_object:
            storage_system_object = get_storage_class()(settings.NEWCCT_UPLOAD_FILE_PATH)  # 设置文件存储路径
            upload_file_object = ContentFile(content=file_object.read(), name=file_object.name)
            storage_system_object.save(name=file_object.name, content=upload_file_object)  # 保存文件
            models.info_test.objects.create(file_name=file_object.name, create_time=date_array,
                                            download_link='http://192.168.0.104:8000/newcct/download/?file=%s'
                                                          % file_object.name)
            return HttpResponse('success')
        else:
            return HttpResponse('fail')
    except Exception as e:
        print(repr(e))
        return HttpResponse(str(e))


def download_file(request):
    """下载文件"""
    try:
        download_filename = request.GET.get('file')
        absolute_location = settings.NEWCCT_UPLOAD_FILE_PATH + download_filename
        file = open(absolute_location, 'rb')
        # response = FileResponse(file)
        # response['Content-Type'] = 'application/octet-stream'
        # return response
        return FileResponse(file)
    except Exception as e:
        print(repr(e))
        return HttpResponse(str(e))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值