首页 > 其他分享 >django保存图片并返回url

django保存图片并返回url

时间:2023-04-16 20:34:40浏览次数:33  
标签:返回 description title url MEDIA image settings django

场景描述

前端传递一个表单,表单中有title,description,以及image等信息,image在这里传递的是二进制文件
后端需要将这些数据保存到一个数据库中。image需要保存到指定文件夹下,并且数据库中保存的是image的路径,
之后我们可以通过浏览器访问 类似 127.0.0.1:8000/xxx/a.jpg 访问到这张图片

步骤

这个问题忙活了很久,网上的说法众说纷纭,借助于ChatGpt才将问题得以解决,我的django版本是4.2

  1. 配置MEDIA的相关信息
    我这里的配置如下:image
    这里的MEDIA_URL就是我们访问时127.0.0.1:8000后面的地址
    这里的MEDIA_ROOT则是图片保存的文件夹
  2. 编写对应的模型,也就是是models.py文件
class ImgSave(models.Model):
    title = models.CharField(max_length=50)
    description = models.TextField()
    imgURL = models.ImageField(upload_to='notices')
  1. 编写对应的视图函数,用户前端提交表单信息。我们要做的就是将图片保存到刚才配置的MEDIA_ROOT文件夹下,并在数据库中存入对应地址。存入的时候我们使用的是FileSystemStorage,Django自带的媒体文件存储类
# 注意自己引入对应的模型以及方法
from .models import ImgSave
from django.conf import settings
from django.core.files.storage import FileSystemStorage
import os
class SaveImg(View):
    def post(self, request):
        # media下面的文件夹名字,可以不写,不写就默认是在media文件夹下
	# 1. 获取post方法传递过来的数据
        file_name = 'notices/'
        title = request.POST.get('title')
        description = request.POST.get('description')
        image = request.FILES.get('image')
        # print(title, description, type(image))
	# 2. 将图片进行保存,可以用with open的方法进行保存,在django中我们直接自带的FIleSystemStorage
        fs = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT,file_name))
        img_name = fs.save(image.name, image)
	# 3. 对url进行处理,保存成我们浏览器可以直接访问的格式
        #  /ip:port + /media/ + /notices/ + a.png
        img_url = '127.0.0.1:8000'+settings.MEDIA_URL+file_name+img_name
        try:
	# 4. 将相关信息保存到数据库
            ImgSave.objects.create(title=title, description=description, imgURL=img_url)
            return JsonResponse({'status':'success','url':img_url},status=200)
        except Exception as e:
            return JsonResponse({'status': 'error', "msg": e}, status=400)

  1. 配置表单提交的接口,这里的知识点不再描述。我使用的是面向对象的方式写的视图,所以写法上跟函数式可能有差别,我的二级路由配置如下:
    image
    仅作参考
  2. 在根路由中配置
    在urlpatterns的数组后面添加上 static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
    列出我项目根路由的信息
    image
    相关代码
from django.urls import path, include
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
    path('admin/', include('BackstageApi.urls')),
    path('test/', include('Testing.urls')),
    path('', include('ForegroundApi.urls')),
]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

结果展示

之后前端通过提交表单的方式将数据进行提交,我们就可以通过返回的url_img数据进行图片的访问
image

image
我这里是因为测试的时候该图片已经上传过一次了,也就是存在同名文件,django后台自动做的处理

前端示例代码

仅供参考

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>Registration Form</title>

    <!-- Import Vue.js from CDN -->
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <!-- Import Bootstrap CSS from CDN -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
    <!-- Import axios from CDN -->
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

</head>


<body>
    <div id="app" class="container">
        <h1>Registration Form</h1>
        <form>
            <div class="mb-3">
                <label for="title" class="form-label">Title</label>
                <input type="text" class="form-control" id="title" v-model="title">
            </div>
            <div class="mb-3">
                <label for="description" class="form-label">Description</label>
                <input type="text" class="form-control" id="description" v-model="description">
            </div>
            <div class="mb-3">
                <label for="image" class="form-label">Image</label>
                <input type="file" class="form-control" id="image" v-on:change="onFileChange">
            </div>
          
            <button type="submit" class="btn btn-primary" v-on:click.prevent="submitForm">Submit</button>
        </form>
    </div>
    <script>
        new Vue({
            el: '#app',
            data: {
                title: '好吃的不得了',
                description: '发射点发射点发射点发法大师傅大师傅撒范德萨',
                image: ''
            },
            methods: {
                onFileChange(e) {
                    this.image = e.target.files[0];
                },
                submitForm() {
                    // Handle form submission here
                    console.log(this.title, this.description, this.image)
                    let formData = new FormData();
                    formData.append('title', this.title);
                    formData.append('description', this.description);
                    formData.append('image', this.image);
                    axios.post('http://localhost:8000/test/upload', formData, {
                        headers: {
                            'Content-Type': 'multipart/form-data'
                        }
                    })
                        .then(function (response) {
                            console.log(response);
                        })
                        .catch(function (error) {
                            console.log(error);
                        });
                }
            }
        });
    </script>

   
    </script>
</body>

</html>

标签:返回,description,title,url,MEDIA,image,settings,django
From: https://www.cnblogs.com/zx529/p/17323978.html

相关文章

  • 如何自行查找出 SAP ABAP 标准的 OData 服务返回数据的后台数据库表和表字段名称
    笔者的知识星球有朋友提问,询问如何查找一个SAPABAPOData服务,暴露出的字段到底来自SAPABAP后台哪些数据库表的哪些字段。要回答这个问题,需要综合运用到我们过去学过的包括ABAP后台程序单步调试的知识。本文我们还是通过之前使用过的SAPCRM标准的Fiori应用,MyAccoun......
  • Django框架基础3
      本节主要分为两个内容:Django模板加载与响应模板精讲(模板变量、模板标签、判断逻辑(if和for))一、Django模板加载与响应  Django的模板系统将Python代码与HTML代码解耦,动态地生成HTML页面。Django项目可以配置一个或多个模板引擎,但是通常使用Django的模板系统......
  • url跳转漏洞
    1、定义url跳转是指的攻击者可以构造payload,使受害者用户在访问目标网站的时候,跳转到攻击者控制的站点,从而进行钓鱼活动。2、发生场景(1)攻击者提前将payload保存到服务端的数据库,或者上传包含某跳转的页面,或者篡改已知页面包含跳转。这些情况有可能,但是一般意义不大。(2)请......
  • how to use cURL with a variable in the URL string All In One
    howtousecURLwithavariableintheURLstringAllInOne如何在cURL的URL字符串中使用变量系统变量环境变量shell变量#cURL字符串中如何使用shell系统环境变量❓$exportDD_ROBOT_TOKEN=404e99******36d17fa1202$echo$DD_ROBOT_TOKEN#404e99*****......
  • django中配置favicon.ico
    方法一:使用重定向在项目的urls.py中添加规则:fromdjango.urlsimportpathfromdjango.views.generic.baseimportRedirectViewurlpatterns=[...path('favicon.ico',RedirectView.as_view(url='static/img/favicon.ico')),]复制这种方式我认为是最......
  • Django练手小项目1:云笔记
    Django练手小项目1:云笔记1、创建项目专业版pycharm:新建项目->Django->路径下加上项目名python环境:manage.pystartproject项目名2、创建数据库,设计表结构3、新建应用专业版:点击:tools->运行manage.py->startapp应用名4、注册应用5、配置数据库6、更......
  • 编写你的第一个 Django 应用程序,第1部分
    让我们通过示例来学习。在本教程中,我们将引导您完成基本投票应用程序它将由两部分组成:一个公共网站,允许人们查看投票并在其中投票。允许您添加、更改和删除投票的管理网站。一、开发环境搭建第一步当然就是安装python,网上教程太多了,不再赘述。第二步当然就是安装django......
  • Android开发,使用的是OkHttp和Reftrofit,用的是Kotlin协程,用Kotlin写一个网络拦截器,模拟
    首先,我们需要定义一个网络拦截器类,继承自OkHttp的Interceptor接口:classLoginInterceptor:Interceptor{overridefunintercept(chain:Interceptor.Chain):Response{//模拟登录请求,这里可以根据具体情况进行修改valrequest=chain.request().ne......
  • Python3基本请求库-urllib
    urlliburlopen一个基本请求fromurllibimportrequest,parsedefApi():#禁用证书验证ssl._create_default_https_context=ssl._create_unverified_contextresponse=request.urlopen('https://www.baidu.com/')print(response.read().decode(�......
  • Django中使用session,并设置过期时间
    Django中session的使用使用背景django中自带了一个数据库,名字是djang_session,用户做用户凭证。它有三个字段session_keysession_dataexpire_data这个数字会返回给客户端存储的相关信息过期时间流程:1.用户首次输入账户名和密码,服务端判断正确之后创建一个sesi......