0
我使用https://github.com/skoczen/django-ajax-uploader在django上傳文件。它的工作原理,但我想在這個過程中重命名上傳的文件。我想添加一個時間戳,所以我確定它有一個唯一的名稱。使用django -ajax-uploader重命名文件
如何做到這一點?
我使用https://github.com/skoczen/django-ajax-uploader在django上傳文件。它的工作原理,但我想在這個過程中重命名上傳的文件。我想添加一個時間戳,所以我確定它有一個唯一的名稱。使用django -ajax-uploader重命名文件
如何做到這一點?
我終於結束了使用jQuery-File-Upload。它允許定義view.Example裏面的文件的路徑:
urls.py
url(r'^upload_question_photo/$', UploadQuestionPhoto.as_view(), name="upload_question_photo"),
的index.html
var input=$(this).find("input");
var formData = new FormData();
formData.append('photo', input[0].files[0]);
formData.append('question', input.attr("name"));
formData.append('csrfmiddlewaretoken', '{{ csrf_token }}');
input.fileupload(
{
dataType: 'json',
url: "{% url 'campaigns:upload_question_photo' %}",
formData: formData,
//the file has been successfully uploaded
done: function (e, data)
{
response=data.result;
window.console&&console.log("Successfully uploaded!");
window.console&&console.log(response.path);
}.bind(this),
processfail: function (e, data)
{
window.console&&console.log('Upload has failed');
}.bind(this)
});
views.py
class UploadQuestionPhoto(View):
u"""Uploads photos with ajax
Based on the code #https://github.com/miki725/Django-jQuery-File-Uploader-Integration-demo/blob/master/upload/views.py
"""
def post(self, request, *args, **kwargs):
print "UploadQuestionPhoto post"
response={}
question=str(request.POST["question"])
#path where the file is going to be stored
path="/question/" + question + "/"
photo_path=settings.MEDIA_ROOT + path
# if 'f' query parameter is not specified -> file is being uploaded
if not ("f" in request.GET.keys()):
print "file upload"
# make sure some files have been uploaded
if request.FILES:
# get the uploaded file
photo_file = request.FILES["question_field_" + question]
name_with_timestamp=str(time.time()) + "_" + photo_file.name
# create directory if not exists already
if not os.path.exists(photo_path):
os.makedirs(photo_path)
# add timestamp to the file name to avoid conflicts of files with the same name
filename = os.path.join(photo_path, name_with_timestamp)
# open the file handler with write binary mode
destination = open(filename, "wb+")
# save file data with the chunk method in case the file is too big (save memory)
for chunk in photo_file.chunks():
destination.write(chunk)
destination.close()
#response sent back to ajax once the file has been successfuly uploaded
response['status']='success'
response["path"]=photo_path+name_with_timestamp
# file has to be deleted (TODO: NOT TESTED)
else:
# get the file path by getting it from the query (e.g. '?f=filename.here')
filepath = os.path.join(photo_path, request.GET["f"])
os.remove(filepath)
# generate true json result (if true is not returned, the file will not be removed from the upload queue)
response = True
# return the result data (json)
return HttpResponse(json.dumps(response), content_type="application/json")
Voilà!希望能幫助到你。