溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Django如何接收照片儲(chǔ)存文件

發(fā)布時(shí)間:2021-06-16 15:17:26 來源:億速云 閱讀:160 作者:小新 欄目:開發(fā)技術(shù)

這篇文章主要介紹Django如何接收照片儲(chǔ)存文件,文中介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們一定要看完!

后端:

from rest_framework.views import APIView
from car import settings
from django.shortcuts import render, redirect, HttpResponse
from dal import models
from django.http import JsonResponse
import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

class Image(APIView):

  def post(self, request):
    file_obj = request.FILES.get('send',None)

    print("file_obj",file_obj.name)

    file_path = os.path.join(BASE_DIR, 'media', 'user/img', file_obj.name)

    print("file_path", file_path)

    with open(file_path, 'w') as f:
      for chunk in file_obj.chunks():
        f.write(chunk)

    message = {}
    message['code'] = 200

    return JsonResponse(message)

前端ajax:

<form method="post" action="/upload/" enctype="multipart/form-data" target="ifm1">
    <input type="file" name="send"/>

    <input type="submit" value="Form表單提交"/>
  </form>

下面在看下在Django中接收文件并存儲(chǔ)

首先是一個(gè)views函數(shù)的例子 

def get_user_profiles(request):
  if request.method == 'POST':
      myFile = request.FILES.get("filename", None)
      if myFile:
        dir = os.path.join(os.path.join(BASE_DIR, 'static'),'profiles')
        destination = open(os.path.join(dir, myFile.name),
                  'wb+')
        for chunk in myFile.chunks():
          destination.write(chunk)
        destination.close()
      return HttpResponse('ok')

這是一個(gè)簡單的接收客戶端上傳的頭像文件并保存的例子,應(yīng)該看過這個(gè)就已經(jīng)大體會(huì)使用接收文件了

但是這里的filename是客戶端上傳的文件名,也可能是像下面這樣的表單 

<input type="file" name="filename" />

如果不知道固定上傳的文件名,想要客戶端上傳什么文件就以其上傳的名字命名可以這么寫

def get_user_profiles(request):
  if request.method == 'POST':
    if request.FILES:
      myFile =None
      for i in request.FILES:
        myFile = request.FILES[i]
      if myFile:
        dir = os.path.join(os.path.join(BASE_DIR, 'static'),'profiles')
        destination = open(os.path.join(dir, myFile.name),
                  'wb+')
        for chunk in myFile.chunks():
          destination.write(chunk)
        destination.close()
      return HttpResponse('ok')

不過這個(gè)是通過輸出request.FILES試出來的,不知道是否有更合適的方法。

以上是“Django如何接收照片儲(chǔ)存文件”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對(duì)大家有幫助,更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI