django接收前端vue传输的formData图片数据

在Django中接收前端Vue传输的formData中的图片数据,通常是通过Django的视图(Views)和表单(Forms)来实现的。下面是一个基本的示例,说明了如何在Django后端处理由Vue前端发送的formData图片。

前端Vue代码示例:

假设你有一个Vue组件,其中包含一个表单,用户可以通过这个表单上传图片:

javascript 复制代码
<template>
  <div>
    <form @submit.prevent="submitForm">
      <input type="file" @change="onFileChange" />
      <button type="submit">上传图片</button>
    </form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      file: null,
    };
  },
  methods: {
    onFileChange(e) {
      this.file = e.target.files[0];
    },
    async submitForm() {
      if (!this.file) {
        alert('请选择一个文件。');
        return;
      }

      const formData = new FormData();
      formData.append('image', this.file);

      try {
        const response = await this.$http.post('/upload/', formData, {
          headers: {
            'Content-Type': 'multipart/form-data',
          },
        });
        console.log('Image uploaded:', response.data);
      } catch (error) {
        console.error('上传失败:', error);
      }
    },
  },
};
</script>

后端Django代码示例:

在Django后端,你需要创建一个视图来处理图片上传:

python 复制代码
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.core.files.storage import default_storage
from django.core.files.base import ContentFile

@csrf_exempt  # 如果你不使用Django的CSRF令牌,则可以暂时禁用CSRF保护
def upload_image(request):
    if request.method == 'POST' and request.FILES['image']:
        image = request.FILES['image']
        image_name = default_storage.save(image.name, ContentFile(image.read()))
        image_url = default_storage.url(image_name)
        return JsonResponse({'message': '图片上传成功', 'url': image_url})
    return JsonResponse({'error': '无法上传图片'}, status=400)

urls.py中,你需要为这个视图添加一个URL路径:

python 复制代码
from django.urls import path
from .views import upload_image

urlpatterns = [
    # ... 其他URL配置 ...
    path('upload/', upload_image, name='upload_image'),
]
相关推荐
爱学习的程序媛44 分钟前
【Web前端】JavaScript设计模式全解析
前端·javascript·设计模式·web
小码哥_常1 小时前
从SharedPreferences到DataStore:Android存储进化之路
前端
老黑1 小时前
开源工具 AIDA:给 AI 辅助开发加一个数据采集层,让 AI 从错误中自动学习(Glama 3A 认证)
前端·react.js·ai·nodejs·cursor·vibe coding·claude code
jessecyj1 小时前
Spring boot整合quartz方法
java·前端·spring boot
苦瓜小生1 小时前
【前端】|【js手撕】经典高频面试题:手写实现function.call、apply、bind
java·前端·javascript
天若有情6732 小时前
前端HTML精讲03:页面性能优化+懒加载,搞定首屏加速
前端·性能优化·html
踩着两条虫2 小时前
AI驱动的Vue3应用开发平台深入探究(十):物料系统之内置组件库
android·前端·vue.js·人工智能·低代码·系统架构·rxjava
swipe2 小时前
AI 应用里的 Memory,不是“保存聊天记录”,而是管理上下文预算
前端·llm·agent
慧一居士2 小时前
nuxt3 项目和nuxt4 项目区别和对比
前端·vue.js
威联通安全存储3 小时前
破除“重前端、轻底层”的数字幻象:如何夯实工业数据的物理底座
前端·python