1.首頁:index.html
<form enctype="multipart/form-data" action="/uploadFile/{{ product_obj.id}}" method="post"> <input type="file" name="myfile" id="avatar_file" /> <br/> <input type="submit" value="upload"> </form>

action依照自己對應的數據庫進行修改。
2.路由:url
url(r'^uploadFile/(\d+)',views.upload_file),

3.視圖:views
def upload_file(request,uid): if request.method == 'POST': myFile = request.FILES.get("myfile",None) print myFile,'++++++++++++++++++++++' if not myFile: return HttpResponse('no files for upload!') Product.objects.filter(id=uid).update(image=myFile.name,jad_address=myFile) destination = open(os.path.join("D:/home/task/media",myFile.name),'wb+') for chunk in myFile.chunks(): destination.write(chunk) print destination,'----------------------' destination.close() return redirect('/index/')
4.配置media
1.在settings里配置:
MEDIA_URL = "/media/" MEDIA_ROOT = os.path.join(BASE_DIR,'media')
2.在url配置
url(r'^media/(?P<path>.*)$',serve,{'document_root':settings.MEDIA_ROOT}),
3.記得導入相對所在包,不然無效。
分析:
文件的上傳流程: 選中本地的圖片,upload點擊進行上傳,
1.先在服務器目錄的media下傳入我們的圖片,
2.然后更新數據庫的記錄信息,因為數據庫的記錄是基於media里的文件,如果有才可展示,否則就不可展示。
下載:
1.首頁:index
<a href="/download/{{ product_obj.jad_address }}"> <button class="btn bg-danger">下載</button> </a>
自己根據自己的數據結構進行相應的修改:a標簽執行路由url
2.路由:url
url(r'^download/(?P<file_name>.*)/$',views.download_file),
分析: 這里帶個參數給后端,url命名分組
3.視圖:views
def download_file(request,file_name): def file_iterator(file_name,chunk_size=512): print file_name,'******************' with open(file_name, 'rb') as f: if f: yield f.read(chunk_size) print '下載完成' else: print '未完成下載' the_file_name = 'D:/home/task/media/'+ file_name print the_file_name,'1111111111111111111111' response = StreamingHttpResponse(file_iterator(the_file_name)) response['Content-Type'] = 'application/octet-stream' response['Content-Disposition'] = 'attachement;filename="{0}"'.format(file_name) return response
