【问题标题】:Could I use InMemoryUploadedFile directly to upload Image to Imgur?我可以直接使用 InMemoryUploadedFile 将图像上传到 Imgur 吗?
【发布时间】:2021-08-19 19:58:36
【问题描述】:

我在使用 Django 将图像上传到 Imgur 时遇到一些问题。

我已经完成了从 react 上传的 Image File 并通过 Axios 将 File 数据传递到后端。

但是我从 Python 后端的 request.data 中得到的对象是InMemoryUploadedFile

我不想在我的磁盘中存储任何图像文件。

我可以直接使用这个InMemoryUploadedFile类型的文件通过Imgur上传功能upload_from_path上传吗?

如果是这样,我该怎么办?

这是我的代码,

from django.shortcuts import render
from django.http import JsonResponse
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated, IsAdminUser
from rest_framework.response import Response

from django.contrib.auth.models import User
from base.models import InCome, IncomeMoneyCategory, IncomeContributeContext,OutcomeMoneyCategory, OutcomeContributeContext, Member, Student, OutCome

from django.db.models import F, Sum
from base.serializers import IncomeSerializer, OutcomeSerializer

from rest_framework import status

from datetime import datetime
import configparser
import base.config as env
import os
from django.core.files.storage import default_storage
from django.core.files.base import ContentFile
from django.conf import settings
from imgurpython import  ImgurClient



@api_view(['POST'])
def upload_image(request):
    
    data = request.data
    
    print(data)
    album = env.IMGUR_ALBUM
    print(data['image'])
    image=data['image']
    print("--")
    print(type(image))
    
    image_path=image

    config = configparser.ConfigParser()
    path = '/'.join((os.path.abspath(__file__).replace('\\', '/')).split('/')[:-1])
    config.read(os.path.join(path, 'auth.ini'))
    #config.read('auth.ini')
    
    client_id = config['credentials']['client_id']
    client_secret = config['credentials']['client_secret']
    refresh_token = config['credentials']['refresh_token']
    access_token = config['credentials']['access_token']
    client = ImgurClient(client_id,client_secret, refresh_token)
    client.set_user_auth(access_token, refresh_token)   

    if client:
        config={
            'album':album,
            'name':'Ezra',
            'title':'Test',
            'description': 'Test {0}'.format(datetime.now())
        }

        print("Uploading image")
        
        image = client.upload_from_path(str(image_path),config=config,anon=False)
        
        print(image['link'])
        print("Done")
        return image

    else:return "Error"

image 的类型是<class 'django.core.files.uploadedfile.InMemoryUploadedFile'>

但是imgurpython包的函数ImgurClient.upload_from_path中的第一个参数需要上传文件名。

所以当我执行这段代码时,我会得到这个错误: No such file or directory:...

希望有人能帮我解决这个问题,对不起我的英语不好。 感谢您的阅读。

【问题讨论】:

    标签: python django imgur


    【解决方案1】:

    我已经解决了。

    我使用default_storage 保存文件并将目录作为upload_from_path 方法中的第一个参数。

    上传到 Imgur 后,我删除了文件并返回链接。

    这是我的代码:

    def upload_image(request):
        
        data = request.data
        
        album = env.IMGUR_ALBUM
        image=data['image']
    
        file = data['image']
    
        filename = default_storage.save(file.name, ContentFile(file.read()))
        
    
        config = configparser.ConfigParser()
        path = '/'.join((os.path.abspath(__file__).replace('\\', '/')).split('/')[:-1])
        config.read(os.path.join(path, 'auth.ini'))
       
        client_id = config['credentials']['client_id']
        client_secret = config['credentials']['client_secret']
        refresh_token = config['credentials']['refresh_token']
        access_token = config['credentials']['access_token']
        client = ImgurClient(client_id,client_secret, refresh_token)
        client.set_user_auth(access_token, refresh_token)   
    
        if client:
            config={
                'album':album,
                'name':'Ezra',
                'title':'Test',
                'description': 'Test {0}'.format(datetime.now())
            }
    
            print("Uploading image")
            
            image = client.upload_from_path(settings.MEDIA_ROOT+'/'+filename,config=config,anon=False)
            
            
            print("Done")
            default_storage.delete(filename)
            return Response(image['link'])
    
        else:return "Error"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-25
      • 1970-01-01
      • 2011-05-20
      • 2016-09-23
      • 2020-11-13
      • 1970-01-01
      • 2011-12-23
      • 2021-06-11
      相关资源
      最近更新 更多