我想上傳沒有模型的文件(文本/圖像)(只是使用視圖和模板)。我最好喜歡讀或寫位置。django上傳沒有模型的文件
我當前的代碼如下:
在我的模板/foo/help/UploadFileContent.html
<!doctype html>
<html>
<body>
<link rel="stylesheet" href="{{STATIC_URL}}/stylesheets/jquery-ui.css">
<div class="main-content">
<div class="container">
<div class="container">
<div class="row">
<div class="box">
<div class="box-content">
<div class="col-md-12">
<form method="post" id="fileupload" action="/helpsubmitfilecontent/" accept-charset="utf-8" class="fill-up">
{% csrf_token %}
<div class="row">
<div class="col-lg-4">
<ul class="padded separate-sections">
<li>
<input type="text" name="name" id="name" placeholder="Name"/>
</li>
<li>
<textarea name="content" id="content"
placeholder="Help Contents" style="height: 250px;width: 700px"></textarea>
</li>
<li>
<input type="file" name="myfile" id="myfile" />
</li>
</ul>
<div class="form-actions">
<button type="submit" class="btn btn-blue">Submit</button>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
<script>
$('#fileupload').submit(function(evnt){
if($('#name').val().length <=0){
$('#name').attr('style','border-color:red');
evnt.preventDefault();
}
if($('#content').val().length <=0){
$('#content').attr('style','border-color:red');
evnt.preventDefault();
}
});
</script>
</html>
在我的幫助的觀點:
def fileupload(request):
return responsewrapper('pages/foo/help/UploadFileContent.html', locals(),request)
def submitfilecontent(request):
myhash = dict()
myhash['name'] = request.POST['name'] # works
myhash['filedata'] = request.POST['content'] # works
handle_uploaded_file(request.FILES['myfile']) # error throws up here.
return HttpResponseRedirect("/successupload")
def handle_uploaded_file(f):
destination = open('/home/foo/name.txt', 'wb+')
for chunk in f.chunks():
destination.write(chunk)
destination.close()
以下錯誤拋出了同時對文件數據進行操作。
Exception Value:
"Key 'myfile' not found in <MultiValueDict: {}>"
請指教。理想情況下,我不想使用任何數據庫,因爲我只想將文本/圖像導入靜態位置。
如何將文件保存到handle_uploaded_file中的/ opt/tmp/foo( f),不想玩settings.py –
你有什麼問題? –
我目前假設用戶輸入是一個文本文件,但它可能是圖像,我想將其存儲到/user/img1.{png/bmp/jpeg/*} –