python - django 使用ajax将图片上传到服务器并渲染到前端

时间:2024-01-31 12:12:40

一。前端代码

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>

<script>
    // 创建一个表单对象(用于存储要发送的data数据)
    form_data = new FormData;    

    // 参数1:后端请求时要获取的参数, 参数2:图片文件File对象
    form_data.append("files", $("#file_img")[0].files[0]);
    
    // 向后端发送 ajax 请求
    $("#btn").click = function(){
        $.ajax({
            url: "/img/save/",
            method: "post",
            contentType: false,        // 告诉jQuery不要去设置Content-Type请求头
            processData: false,        // 告诉jQuery不要去处理发送的数据
            data: form_data,
            success: function(data){
                console.log("上传成功!");
            }, error: function(data){
                console.log("上传失败!");
            }
        })
    }

</script>    

<body>
    
    <form>
        <input type="file" id="file_img">
        <input type="button" value="提交" id=btn>
    </form>    

</body>
</html>

 

二。后端代码。

# 1. settings  设置图片保存路径
MEDIA_URL = \'/media/\'
MEDIA_ROOT = os.path.join(BASE_DIR, "up_img")

# 2. models
class Image(models.Model):
    path_and_rename = PathAndRename("order/pho") 
                # 图片存储路径 - 最终呈现路径:/up_img/order/pho/xx.jpg image = models.ImageField(verbose_name=u"图片", upload_to=path_and_rename) # 3. url url(r\'^img/save/$\', surface_save, imgViews), # 4. views def imgViews(request): file_img = request.FILES.get(\'files\', None) filename, full_filename = save_image(file_img) Image.objects.create(image=filename) # 定义一个保存图片的方法 def save_image(files): filename = "%s.%s" % (timezone.now().strftime(\'%Y%m%d%H%M%S%f\'), files.name.split(\'.\')[-1]) full_filename = "%s/%s" % (settings.MEDIA_ROOT, filename) with open(full_filename, \'wb+\') as destination: for chunk in files.chunks(): destination.write(chunk) return filename, full_filename

 

三。前端渲染

<img src="{{ img_obj.image.url }}" alt="">

# {{ img_obj.image.url }} 拿出来的是图片路径, img_obj是models中Image表对象

 

# 2. models