[英]Django - how to correctly upload and handle a file?
我有以下apk模型, package_name和sdk_version将通过解析用户将要上传的apk文件来获取。 我还需要在模型中保存上载文件的路径,这就是为什么我使用FilePathField的原因,但是我不确定这是处理任务的正确方法。 我看到了一些使用FileField的示例,这让我感到困惑,什么时候使用哪个? 还有一点,由于路径只是一个字符串,我可以将其另存为Charfield ,不是吗?
class Apk(models.Model):
package_name = models.CharField(max_length=45, unique=True)
sdk_version = models.CharField(max_length=45, unique=True)
apk_file = models.FilePathField()
要上传文件,我使用了本指南。
views.py:
def upload_apk(request):
handle_uploaded_file(request.FILES['file'], str(request.FILES['file']))
return HttpResponse("Upload Successful")
def handle_uploaded_file(file, filename):
if not os.path.exists('policies/upload/'):
os.mkdir('policies/upload/')
with open('policies/upload/' + filename, 'wb+') as destination:
for chunk in file.chunks():
destination.write(chunk)
apk_path = "/policies/upload/" + filename
apkf = APK(apk_path)
package_name = apkf.get_package()
sdk_version = apkf.get_androidversion_name()
template.html:
<form id="uploadApkForm" action="{{ request.build_absolute_uri }}uploadApk/" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<div class="input-element" style="border:1px solid black; background:white; padding:2px">
<input type="file" name="file" style="width:100%" required>
</div>
<div style="width:100%;">
<div style="position: absolute;
left: 50%;
bottom: 0px;
transform: translate(-50%, -50%);
margin: 0 auto;">
<input id="uploadBtn" type="submit" value="Ok" class="btn btn-primary" style="width:75px; margin-right:10px" />
<input id="clsBtn" type="button" class="btn btn-primary" value="Cancel" style="width:75px; "/>
</div>
</div>
</form>
我看到了使用ModelForm的不同示例,但不确定我上传文件的方式是否正确。 您能否指出上载文件并将其路径保存在数据库中的最佳方法是什么?
我认为,使用FileField
可能是最简单的。 使用文件字段,它实际上会将文件保存在特定位置,并允许您将文件用作对象,而不仅仅是简单的路径。 使用filefield,它也使您能够访问路径。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.