def file_upload(request, template_name='oms_config/file_upload_form.html'): var4 = 'active' s = .objects.all() # repository = Repository.objects.all() username = request.session['username'] if request.method == 'POST': form = UploadForm(request.POST, request.FILES) if form.is_valid(): # print form new_file = Upload( doc_file=request.FILES['doc_file'], s_id=request.POST['s'], title=request.POST['title'] ) new_file.save() # handle_uploaded_file(request.FILES['file']) return redirect('upload_list') else: form = UploadForm() return render(request, template_name, {'form': form, 'var4': var4, 'username': username, 'highlight3': 'active', 's': s, })
def upload_file(request): resp = {} url = str(request.get_full_path()) pid = url.split("/")[-1] try: if request.method == 'POST': form = UploadForm(request.POST, request.FILES) if form.is_valid(): #获取表单信息 xlsfile = form.cleaned_data['Filedata'] filename = xlsfile.name #写入数据库 uf = Upload(Filedata = xlsfile, uptime = datetime.datetime.now()) uf.save() filepath = uf.Filedata uipath = unicode(str(filepath), "utf8") uipath = os.path.join(settings.MEDIA_ROOT,uipath) excel_table_byindex(request,file= uipath, pid = pid) resp['success'] = True else: form = UploadForm() except Exception,e: info = "%s" % (sys.exc_info()[1]) resp['success'] = False resp['message'] = info
def upload(): if request.method == 'POST' and 'photo' in request.files: filename = uploads.save(request.files['photo']) rec = Upload(image_url=filename) rec.save() flash("Photo saved.") return redirect(url_for('galeria')) return render_template('upload.html')
def upload(): if request.method == 'POST' and 'photo' in request.files: filename = uploads.save(request.files['photo']) rec = Upload(image_url=filename) rec.save() flash("Photo saved.") return redirect(url_for('galeria')) return render_template('upload.html')
def SaveDoc(uploaded_file_url, dateup): try: sv = Upload( pic=uploaded_file_url, upload_date=dateup, ) sv.save() return True except: return False
def upload(request): if request.method == 'POST': form = FileUploadForm(request.POST, request.FILES) if form.is_valid(): f = Upload() f.filename = form.cleaned_data['file'] f.save() # messages.add_message(request, messages.SUCCESS, u'文件 {0} 上传成功, 大小为{1}KB'.format(f.filename.name.split('/')[-1], int(f.filename.size)/1024)) # return HttpResponseRedirect(reverse('push')) return HttpResponse(u'文件 {0} 上传成功, 大小为{1}KB'.format(f.filename.name.split('/')[-1], int(f.filename.size)/1024))
def upload_video(request): if request.method == 'POST': try: callback_url = '' # for now # Create and populate a new model object upload = Upload(video_title=request.FILES['file'].name, video_file=request.FILES['file'], image_title='', image_file=None, status=Status.video_recieved.value, callback_url=callback_url) # For now upload.save() return HttpResponse(upload.id, status=202) except Exception: return HttpResponseBadRequest('Malformed data.') return HttpResponseNotAllowed('Only POST allowed.')
def upload_action(request): upload_path = '/data/deploy/OMS/media/Upload' files = request.FILES.getlist('doc_file') for item in files: if not os.path.exists(upload_path): makedir_p(upload_path) def handle_uploaded_file(f): with open(upload_path + '/' + f.name, 'wb+') as destination: for chunk in f.chunks(): destination.write(chunk) handle_uploaded_file(item) uploads = Upload( doc_file=os.path.join(upload_path, item.name), s_id=request.POST['s'], title=request.POST['title'] ) uploads.save() return HttpResponse("File(s) uploaded!")
def manageReportUpload(request, cloudItem): """ Uncrypt and store the report """ #check if an item is already in the DB impDb = Upload.objects.filter(cloudItemID=CloudItem.objects.get( id=cloudItem)) if len(impDb) != 0: raise ("A report already exists.") # add path for crypto cryptoPath = os.path.join(os.path.dirname(settings.BASE_DIR), "finder") if not cryptoPath in sys.path: sys.path.insert(1, cryptoPath) del cryptoPath import crypto fileUpload = request.FILES['fileUp'] fileName = strip_tags(fileUpload.name) #create a folder for this cloud item if do not exists path = os.path.join(settings.UPLOAD_DIR, cloudItem) if not os.path.isdir(path): os.mkdir(path) #upload name upTime = timezone.now() shaName = fileName uploadName = crypto.sha256(shaName[:-8] + crypto.HASH_SEPARATOR + format(upTime, "U")).hexdigest() wholeUploadPath = os.path.join(path, uploadName) if not os.path.isdir(wholeUploadPath): os.mkdir(wholeUploadPath) #write to disk with open(os.path.join(wholeUploadPath, fileName), 'wb+') as destination: for chunk in fileUpload.chunks(): destination.write(chunk) fileCont = open(os.path.join(wholeUploadPath, fileName), "r") jsonParsed = json.load(fileCont) cont = jsonParsed['enc'] k = jsonParsed['k'] #decrypt AES key aes = crypto.decryptRSA(k) #decrypt ZIP - first write encrypted cont into a temp file, read it, decrypt it and store the ZIP tempFileName = os.path.join(wholeUploadPath, fileName + ".tmp") open(tempFileName, "w+b").write(cont) # fernet wants "bytes" as token fileBytes = crypto.decryptFernetFile(open(tempFileName, "rb").read(), aes) if fileName.endswith(".enc"): name = fileName[:-4] else: raise Exception("Invalid filename.") #write decrypted file to disc decZipFile = os.path.join(wholeUploadPath, name) open(decZipFile, "w+b").write(fileBytes) #delete temp file os.remove(tempFileName) aes = None del aes #unzip fileZip = zipfile.ZipFile(decZipFile) fileZip.extractall(wholeUploadPath) # set this report parsed newUpload = Upload(fileName=name[:-4], uploadDate=upTime, uploadIP=request.META['REMOTE_ADDR'], parsed=True, cloudItemID=CloudItem.objects.get(id=cloudItem)) newUpload.save()
def user_bio(request): """ 'my_account' view used to handle avatar image upload and routing and templating of users account Args: None Returns: form for avatar upload """ email = request.user.email if request.method == 'POST': imageupload = UploadForm(request.POST, request.FILES) if imageupload.is_valid(): u = imageupload.save(commit=False) #image upload to google cloud storage uploaded_file = request.FILES['image'] content_type = request.FILES['image'].content_type name = request.FILES['image'].name data = uploaded_file.read() gcs_file = gcs.open( ('/' + bucket_name + '/' + name), mode = 'w', content_type = 'image/jpeg', options = { 'x-goog-acl': 'bucket-owner-full-control' } ) gcs_file.write(data) gcs_file.close() #get_serving_url from google and stats #avatar = gcs.open('/' + bucket_name + '/' + name) blob_key = blobstore.create_gs_key( '/gs/' + bucket_name + '/' + name ) serving_url = get_serving_url(blob_key) #find existing avatar image try: u = Upload.objects.get(email = email, is_avatar = True) except Upload.DoesNotExist: u = False #set is_avatar to False but keep entry in db if u: u.is_avatar = False u.save() #insert the uploaded avatar u = Upload(url = serving_url, email = email, is_avatar = True) u.save() stats = gcs.stat('/' + bucket_name + '/' + name) return HttpResponseRedirect('/my_account/') else: form = UploadForm() gallery_form = GalleryForm() try: u = Upload.objects.get(email = email, is_avatar = True) serving_url = u.url except Upload.DoesNotExist: serving_url = '/static/bio/blank.png' return render_to_response( 'profile.html', { 'form': form, 'gallery_form': gallery_form, 'serving_url': serving_url, 'user': email, }, context_instance = RequestContext(request) )
def manageReportUpload(request,cloudItem): """ Uncrypt and store the report """ #check if an item is already in the DB impDb = Upload.objects.filter(cloudItemID=CloudItem.objects.get(id=cloudItem)) if len(impDb) != 0: raise ("A report already exists.") # add path for crypto cryptoPath = os.path.join(os.path.dirname(settings.BASE_DIR), "finder") if not cryptoPath in sys.path: sys.path.insert(1, cryptoPath) del cryptoPath import crypto fileUpload = request.FILES['fileUp'] fileName = strip_tags(fileUpload.name) #create a folder for this cloud item if do not exists path = os.path.join(settings.UPLOAD_DIR,cloudItem) if not os.path.isdir(path): os.mkdir(path) #upload name upTime = timezone.now() shaName = fileName uploadName = crypto.sha256(shaName[:-8]+crypto.HASH_SEPARATOR+format(upTime,"U")).hexdigest() wholeUploadPath = os.path.join(path,uploadName) if not os.path.isdir(wholeUploadPath): os.mkdir(wholeUploadPath) #write to disk with open(os.path.join(wholeUploadPath,fileName), 'wb+') as destination: for chunk in fileUpload.chunks(): destination.write(chunk) fileCont = open(os.path.join(wholeUploadPath,fileName), "r") jsonParsed = json.load(fileCont) cont = jsonParsed['enc'] k = jsonParsed['k'] #decrypt AES key aes = crypto.decryptRSA(k) #decrypt ZIP - first write encrypted cont into a temp file, read it, decrypt it and store the ZIP tempFileName = os.path.join(wholeUploadPath,fileName+".tmp") open(tempFileName, "w+b").write(cont) # fernet wants "bytes" as token fileBytes = crypto.decryptFernetFile(open(tempFileName, "rb").read(), aes) if fileName.endswith(".enc"): name = fileName[:-4] else: raise Exception("Invalid filename.") #write decrypted file to disc decZipFile = os.path.join(wholeUploadPath, name) open(decZipFile, "w+b").write(fileBytes) #delete temp file os.remove(tempFileName) aes = None del aes #unzip fileZip = zipfile.ZipFile(decZipFile) fileZip.extractall(wholeUploadPath) # set this report parsed newUpload = Upload(fileName=name[:-4],uploadDate=upTime,uploadIP=request.META['REMOTE_ADDR'],parsed=True,cloudItemID=CloudItem.objects.get(id=cloudItem)) newUpload.save()