python - django 使用ajax將圖片上傳到服務器並渲染到前端


一。前端代碼

<!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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM