前端源碼:
<!DOCTYPE html>
<html>
<head>
<title>編輯商品分類</title>
<link rel="stylesheet" type="text/css" href="https://cdn.bootcss.com/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<div class="container-fluid">
<div class="row">
<div class="box">
<div class="box-header">
{#路徑導航#}
<ol class="breadcrumb">
<li><a href="#">產品管理</a></li>
<li><a href="#">分類列表</a></li>
<li class="active">會員編輯</li>
</ol>
{#路徑導航#}
</div>
<div class="box-body">
<div class="col-md-12">
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
<div class="form-group">
<label for="username">商品分類名稱</label>
<input type="text" class="form-control" name="name" id="username" value="{{ type.name }}">
</div>
<div class="form-group">
<label for="exampleInputPassword1">原圖片</label>
<a href=""
style="width:155px;height:115px;display:block;text-align:center;border:1px solid red;position:relative;background:url({{ type.img.url }}) no-repeat;">
<input type="file" style="position: absolute;width:155px;height:115px;top:0px;left:0px;filter:alpha(opacity=0);
cursor:pointer;overflow: hidden;opacity: 1; " name="upload_media" id="upload_media" multiple="multiple" >
</a>
</div>
<button type="submit" class="btn btn-default">編輯</button>
</form>
</div>
</div>
</div>
</div>
</div>
</body>
<script type="text/javascript" src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.bootcss.com/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script>
$(function () {
$('.img-thumbnail').click(function () {
console.log('點擊了')
$('.upload_media').change(function () {
console.log('deeee')
})
});
$('#upload_media').change(function () {
var $formData=new FormData();
var img_file = $('#upload_media')[0].files[0];
$formData.append("img_file",img_file);
$.ajax({
url: "{% url 'admincms:upload_file' %}",
type: "POST",
data: $formData,
contentType: false,
processData: false,
headers: {"X-CSRFToken": $('[name="csrfmiddlewaretoken"]').val()},
success: function (data) {
//$(".error_msg").text(data)
console.log(data)
},
error:function(data){
console.log(data)
}
})
});
});
</script>
</html>
視圖源碼:
#上傳圖片 def upload_file(request): fafafa = request.FILES.get('img_file') print(fafafa) print(fafafa.name) import os img_path = os.path.join('static/media/',fafafa.name) #存儲的路徑 with open(img_path,'wb') as f: #圖片上傳 for item in fafafa.chunks(): f.write(item) ret = {'code': True , 'data': img_path} #'data': img_path 數據為圖片的路徑, import json return HttpResponse(json.dumps(ret)) #將數據的路徑發送到前端
