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'),
]
相关推荐
践行见远6 分钟前
django之配置文件加载
django
人间凡尔赛20 分钟前
2026 前端必修:4 个让 CSS 脱胎换骨的现代新特性(附实战代码)
前端·css
用户21816970493030 分钟前
Flutter (二十) 轮播图
前端
前端snow36 分钟前
ai agent - RAG 汇总
前端
计算机魔术师1 小时前
AI为拿高分不惜入侵网站:22个模型作弊审计,真相让人背脊发凉
前端
晓说前端1 小时前
TypeScript 核心语法应用 —— Vue 3 中的使用(下)
前端·javascript·typescript·类型系统
zhangminghuan1 小时前
微信小程序开发核心知识点全景解析(前端必备硬核基础)
前端·微信小程序·小程序
boooooooom2 小时前
尝尝咸淡:从朴素 RAG 到 Graph RAG——一个烹饪问答系统的三层检索升级之路
前端·后端·llm
cindershade2 小时前
让每条前端异常都能回答:该由谁修、为什么现在修
前端
bitbrowser2 小时前
Telegram提示尝试次数过多,换网络和重装有用吗
前端