django开发上传文件接口

1.view.py

import json
import os.path

from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.
from blog.models import FileUpload
from mysite.settings import BASE_DIR


def upload(req):
    if req.method == "GET":
        return render(req, "upload.html")
    elif req.method == "POST":
        files = req.FILES.get("file", None)
        save_path = os.path.join(BASE_DIR,"file")
        if not os.path.exists(save_path):
            os.makedirs(save_path)
        file_path = os.path.join(save_path, files.name)
        with open(file_path, "wb") as fp:
            for content in files.chunks():
                fp.write(content)
        obj = FileUpload.objects.create(name=files.name)
        return HttpResponse(json.dumps({"id":obj.id, "name":files.name}, ensure_ascii=False),
                            content_type="application/json,charset=utf-8")


2. upload.html


<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>上传图片title>
head>
<body>
<form action="/upload/" method="post" enctype="multipart/form-data">
        <p align="center"><input type="file" name="file" />p>
        <p align="center"><input type="submit" value="上传" />p>
form>
body>
html>

3. 测试

1.访问并上传http://127.0.0.1:8888/upload/
django开发上传文件接口_第1张图片
2.接口响应内容
django开发上传文件接口_第2张图片

你可能感兴趣的:(Django,django,上传文件接口,json)