首先要先設定models.py
再來是Html網頁部分:
再來是JavaScript網頁部分(請自己先去下載AjaxFileUpload.js模組):
再來是Django部分:
import os from apps.common.templatetags.utiltags import thumb from apps.common.lib import calsize def _FILE_UPLOAD_TO(instance, filename): return os.path.join('apps', 'your_app_name', 'media', 'your_app_name', 'photo_file', str(upload_date), str(instance.id)+'.'+instance.ext) class PhotoFile(M.Model): #督導缺失相片上傳區 name = M.CharField(verbose_name='檔案名', max_length=256, null=True, default='') ext = M.CharField(verbose_name='副檔名', max_length=10, null=True) upload_date = M.DateField(verbose_name='上傳日期') file = M.ImageField(upload_to=_FILE_UPLOAD_TO, null=True) memo = M.CharField(verbose_name='備註說明', null=True, max_length=2048) def rUrl(self): return self.file.name.split('apps/your_app_name/')[-1] def rThumbUrl(self): thumbsrc = thumb(self.file.name, "width=1024,height=768") if thumbsrc == 'media/images/error.png': return self.file.name.split('apps/your_app_name/')[-1] else: return thumbsrc.split('apps/your_app_name/')[-1] def rExt(self): return self.file.name.split('.')[-1].lower() def calSize(self): if self.file: return calsize(self.file.size) else: return calsize(0)
再來是Html網頁部分:
<input id="newfile_name" name="newfile_name" type="text"/> <input id="newfile_file" name="newfile_file" type="file"/> <input id="upload_File" type="submit" value="確定上傳" />
再來是JavaScript網頁部分(請自己先去下載AjaxFileUpload.js模組):
$("#upload_File").click(upload_File); function upload_File() { var $obj = $(this); var name = $('#newfile_name').attr('value'); var file = $('#newfile_file').attr('value'); var ext = $('#newfile_file').attr('value').split('.'); ext = ext[ext.length-1].toLowerCase(); if (!file){ alert('請選擇檔案!!!') return false; } if (!confirm('確定上傳 '+file+' ? 按下確定後開始上傳,請勿關閉此頁面!!')){ return false; } $.ajaxFileUpload({ url: '/your_app_name/upload_file/?name=' + name, async: true, fileElementId: 'newfile_file', dataType: 'json', success: function (json, status) { if (json['status'] == false){ alert(json['message']); } else { alert('上傳成功'); } }, error: function (json, status, e) { } }); }
再來是Django部分:
第一部分是urls.py
urlpatterns = patterns('apps.project.views', (r'^upload_file/$', 'uploadFile'), )
第二部分是views.py
import datetime def TODAY(): return datetime.datetime.today() def uploadPhotoFile(R): name = R.GET.get('name') file = R.FILES.get('newfile_file', None) try: extension = file.name.split('.')[-1].lower() except: extension = 'zip' row = PhotoFile( name = name, ext = extension, upload_date = TODAY(), ) row.save() if file: getattr(row, 'file').save('%s.%s'%(row.id, extension), file) row.save() return HttpResponse(json.dumps({'status': True}))
全站熱搜
留言列表