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