Beispiel #1
0
def upload(request):
    path = u'/'
    base_uplod_path = settings.FILEBROWSER['upload_dir']
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)

        if form.is_valid():
            path = form.cleaned_data['path'].encode(FILE_NAME_ENCODING)
            upload_path = base_uplod_path + path
            file_name = request.FILES['file'].name
            if os.path.isfile(upload_path + '/' +
                              file_name.encode(FILE_NAME_ENCODING)):
                return HttpResponse(
                    _(u'File with this name already exist. Please, delete old file or rename uploadable file.'
                      ))
            elif os.path.isdir(upload_path + '/' +
                               file_name.encode(FILE_NAME_ENCODING)):
                return HttpResponse(
                    _(u'Directory with this name already exist. Please, delete old directory or rename uploadable file.'
                      ))

            if not os.path.isdir(upload_path):
                raise Http404(u"Path not founded")

            handle_uploaded_file(f=request.FILES['file'], path=upload_path)

    return HttpResponseRedirect(
        reverse('filebrowser:administration:index') + '?path=' +
        path.decode(FILE_NAME_ENCODING))
Beispiel #2
0
def upload(request):
    print "uploading"
    profile_link = ""
    if request.method == 'POST':
        print "posting"
        print request.POST
        #print type(request.FILES['pic'].get('content_type'))
        #print type(request.FILES['pic']['file'])
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            print 'valid form'
            k = Key(bucket)
            k.key = request.user.username
            k.set_contents_from_file(request.FILES['pic'])
            print "upload!"
            profile_link = "https://s3.amazonaws.com/image-availabook/" + request.user.username
            profile_link = profile_link.replace('@','%40')
            print "link", profile_link
            uploaded = Users.update_image_by_id(request.user.username, profile_link)
            print uploaded
            #print k.get_contents_to_filename
        else:
            print 'invalid form'
            print form.errors
    return redirect("/availabook/profile")
Beispiel #3
0
    def post(self, request):
        form = UploadFileForm(request.POST, request.FILES)
        msg = ''

        if form.is_valid():
            test = Test(
                start_time = convert_time(form.cleaned_data['start']),
                end_time = convert_time(form.cleaned_data['end']),
                author_id = UserProfile.objects.get(user__id=request.user.id),
                time = int(form.cleaned_data['time'])
                )
            test.save()
            try:
                test.room = Room.objects.get(id=form.cleaned_data.get('room'))
            except:
                test.room = None
            finally:
                test.save()
            try:
                self.handle_uploaded_file(test.id, request.FILES['file'])
            except:
                test.delete()
                msg = {'error': 'Wystąpił konflikt terminów. Test nie został dodany.'}
                return render(request, self.template_name, {'form': form, 'msg': msg})

            else:
                test.name = self.get_test_name_from_file(test.id)
                test.save()
            return HttpResponseRedirect(reverse('tests'))
        else:
            msg = {'error': u'Wystąpił błąd podczas ładowania pliku.'}
            form = UploadFileForm()
            return render(request, self.template_name, {'form': form, 'msg': msg})
Beispiel #4
0
def home(request):
    form = UploadFileForm(request.POST or None, request.FILES or None)
    if form.is_valid():
        form.my_save(request)
        return redirect('/')
    else:
        return render(request, "index.html", {"form": form})

# @login_required()
# def userfiles(request):
#     files = DropObjet.objects.filter(user=request.user)
#     #files = DropObjet.objects.all()
#     for file in files:
#         print file.name
#     return render(request, "userfiles.html", {'files': files})
#
# @login_required()
# def show_file(request):
#     name = request.GET.get('name')
#     #name = name.replace('_', ' ')
#     print name
#     print 'Good'
#     file = get_object_or_404(DropObjet, name=name, user=request.user)
#     client = dropbox.client.DropboxClient(settings.AUTH_TOKEN)
#     shared_url = client.share(file.get_path(), short_url=True)
#     print shared_url['url']
#     return render(request, "show_file.html", {'link': shared_url['url']})
Beispiel #5
0
def upload(request):
    c = RequestContext(request)
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            if 'adicional' in request.FILES:
                code = handle_uploaded_file(request.FILES['apk'],
                                            request.FILES['adicional'])
            else:
                code = handle_uploaded_file(request.FILES['apk'])
            if code == 0:
                return HttpResponseRedirect('/success/upload/')
            elif code == 1:
                return HttpResponseRedirect('/error/duplicated/')
            elif code == 2:
                return HttpResponseRedirect('/error/upload/')
        else:
            pass
            #return HttpResponseRedirect('/error/upload/')

    else:
        form = UploadFileForm()

    return render_to_response('upload.html', {
        'err': False,
        'form': form
    },
                              context_instance=c)
Beispiel #6
0
def upload_file(request):
    error=None
    if request.method=='POST':
	upload_form=UploadFileForm(request.POST,request.FILES)
	if upload_form.is_valid():
	    client=SaltByLocalApi('/etc/salt/master')
	    target=upload_form.cleaned_data['target']
	    mapping=upload_form.cleaned_data['mapping']
	    upload_path=upload_form.cleaned_data['upload_path']
	    if not is_exist_minion(client,target,mapping) or not request.user.is_superuser:
		error='主机名中存在离线主机,请确认后再上传'
		return render_to_response('upload_file.html',RequestContext(request,{'form':upload_form,'error':error}))
	    else:
		f=request.FILES.get('upload_file',None)
		if not f:
		    return render_to_response('upload_file.html',RequestContext(request,{'form':upload_form,'error':'文件损坏'})) 
		tmp_path=os.path.join('/tmp/',f.name)
		with open(tmp_path,'wb+') as tmp_file:
		    for chunk in f.chunks():
			tmp_file.write(chunk)
		if not os.path.exists('/srv/salt/upload'):
		    os.system('mkdir -p /srv/salt/upload')
		cmd="mv {} /srv/salt/upload/".format(tmp_path)
		os.system(cmd)
		file_path=os.path.join(upload_path,f.name)
		bak_file_path=file_path+'.bak'
		bak_cmd='rm -f %s && cp  %s %s' %(bak_file_path,file_path,bak_file_path)
		client.client.cmd(target,'cmd.run',[bak_cmd],expr_form=mapping)
		output=client.client.cmd(target,'cp.get_file',['salt://upload/'+f.name,file_path,'makedirs=True'],expr_form=mapping)
		DistributeFileRecordModel.objects.create(user=request.user.username,hostname=target,pattern=mapping,path=file_path,filename=f.name,opttime=datetime.now())
		return render_to_response('upload_file.html',RequestContext(request,{'form':upload_form,'error':error,'result':output,'status':200}))
        else:
	    return render_to_response('upload_file.html',RequestContext(request,{'form':upload_form,'cmd_error':'请选择上传的文件!'}))
    upload_form=UploadFileForm()
    return render_to_response('upload_file.html',RequestContext(request,{'form':upload_form,'error':error}))
Beispiel #7
0
def api_upload(request):
    if request.method == 'POST':
        picture = Picture()
        user = User.objects.get(email=request.POST['email'])
        picture.user = user
        form = UploadFileForm(request.POST, request.FILES, instance=picture)
        if form.is_valid():
            picture.picture = request.FILES['picture']
            if request.POST.has_key('gallery_id'):
                gallery = Gallery.objects.get(id=request.POST['gallery_id'], user=user)
                picture.gallery = gallery

            picture.picture.name = unidecode(picture.picture.name)
            picture.save()
            rotate_picture(picture)
            picture.update_thumb()

            if request.POST.has_key('description'):
                picture_description = PictureDescription(picture=picture)
                picture_description.text = request.POST['description']
                picture_description.save()  

            response = {'status':'OK'}
            response['data'] = serialize_picture(picture)
            return HttpResponse(json.dumps(response))

    return HttpResponse(content_200)
def main(request):
    if not request.user.is_authenticated():
        return HttpResponseRedirect('/',RequestContext(request))

    path = '{}/media/files'.format(os.getcwd())
    file_list = list(os.listdir(path))

    form_1 = UploadFileForm()
    form_2 = UploadDocForm()

    if request.method == 'POST':
        form_1 = UploadFileForm(request.POST, request.FILES)

        if form_1.is_valid():
            new_file = UploadFile(file=request.FILES['file'])
            new_file.save()
            filename = request.FILES['file'].name
            #handle_uploaded_file(request.FILES['file'])
            data = {'name':filename}
            return HttpResponse('Form_1 post file and form is_valid')
    else:
        form_1 = UploadFileForm()


    data = {'form_1': form_1, 'file_list':file_list }
    return render(request,'vedio_parser/vedio_parser_main.html', data)
Beispiel #9
0
def upload_customer_report(request):
    result = ""

    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if (form.is_valid()):
            upload_file = request.FILES['upload_file']
            filename = upload_file.name
            store_path = os.path.join(config.WORKING_DIR, filename)
            store_file = open(store_path, "wb")

            #upload_file.read()
            for content in upload_file.chunks():
                store_file.write(content)
                #print content[:100]

            store_file.close()
            #result = filename + " is uploaded successfully"
            result = "ok"
        else:
            result = "invalid upload"

        return HttpResponse(result)

    else:
        form = UploadFileForm()
        return render_to_response( "upload_customer_report.html",
                {"upload_customer_report_form":form },
            context_instance=RequestContext(request) )
Beispiel #10
0
def upload_file(request, pk):
    #获得一个任务的实例
    task_ins = get_object_or_404(Task, pk=pk)

    #如果获取到了POST的提交
    if request.method == 'POST':
        #获取form表单,request.FILES是存放文件的地方
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            #通过处理上传文件函数来获得返回值
            uf = handle_uploaded_file(request.FILES['file'])

            #获取上传文件的实例,并补充相应信息至数据库中
            upload_ins = Upload()
            #绑定相应的task id
            upload_ins.task_id = task_ins.id
            #记录相应的文件名
            upload_ins.upload_title = uf[0]
            #记录相应的上传路径
            upload_ins.upload_path = uf[1]
            #保存upload的实例
            upload_ins.save()
            return redirect('task_edit', pk=task_ins.id)
    else:
        form = UploadFileForm()

    #构建相应的context,传递至上传文件页面
    context = {
        'form': form,
        'page_title': '任务处理',
        'sub_title': '上传文件',
    }
    return render(request, 'upload.html', context)
Beispiel #11
0
def test_case_upload(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        print form.is_valid()
        if form.is_valid():
            upload_file = request.FILES["uploadfile"]
            try:
                base_dir = os.path.dirname(os.path.abspath(__file__))
                #注意upload前面不能加//
                #upload_file.name 读取上传文件的文件名(包括扩展名),
                #upload_file.read():从文件中读取整个上传的数据,这种方法只适合小文件
                #upload_file.chunks():按块返回文件,通过在for循环中进行迭代,可以将大文件按块写入到服务器中
                #upload_file.multiple_chunks():这个方法根据upload_file的大小,返回True或者False,当upload_file文件大于2.5M(默认为2.5M,可以调整)时,返回True,否则返回False
                #upload_file.size 获取上传文件的大小
                destination = open(
                    os.path.join(base_dir, "upload//%s" % upload_file.name),
                    'wb+')
                if upload_file.multiple_chunks() == False:
                    destination.write(upload_file.read())
                    print "2.5<"
                else:
                    for chunk in upload_file.chunks():
                        destination.write(chunk)
                    print ">2.5"
                destination.close()
                return render(request, 'H/userList.html', {"info": "上传文件成功"})
            except Exception, e:
                print "%s" % e
                return render(request, 'H/userList.html',
                              {"info": "上传文件失败,请重新上传"})
        else:
            return render(request, 'H/userList.html', {"info": "请上传文件"})
Beispiel #12
0
def process_file(request):
    json = {'results': {}, 'error': {}, 'session': {}, 'login': {}}
    log_form = login_form()
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            data = handle_uploaded_file(request.FILES, request.session,
                                        request.user)
            hash = data.file_md5
            return HttpResponseRedirect(reverse('report', args=[hash]))
        else:
            json['error'] = "no file found"
            return render_to_response('error.html',
                                      json,
                                      context_instance=RequestContext(request))

    else:
        json['error'] = "processing file failed"
        return render_to_response('error.html',
                                  json,
                                  context_instance=RequestContext(request))

    return render_to_response(
        'report.html', {
            'results': simplejson.dumps(data, cls=DjangoJSONEncoder),
            'login': log_form
        },
        context_instance=RequestContext(request))
Beispiel #13
0
def add_avatar(request):
	#get image from client
	#save image to media folder
	if request.method == "POST":
		logger.debug("[photo]request POST form: "+ str(request.POST))
		form = UploadFileForm(request.POST, request.FILES)
		logger.debug("[photo]request FILES form: "+ str(request.FILES))

		user_name = request.POST.get('username')
		logger.debug("user name: "+user_name)
		if form.is_valid() and form.is_multipart():
			logger.debug("[photo]upload image: "+str(request.FILES))
			save_file(request.FILES['image'])

			# save image path to avatar url
			client_user = User.objects.get(username = user_name)
			client_info = UserInfo.objects.get(user=client_user)
			client_info.avatar.save(request.FILES['image'].name, request.FILES['image'])
			client_info.save()

			return HttpResponse(200)
		else:
			return HttpResponse('invalid image')

	if request.method == "GET":
		return render(request, 'times/photo.html')
Beispiel #14
0
def upload(request):
    if request.method != 'POST':
        return redirect('index')

    form = UploadFileForm(request.POST, request.FILES)
    if form.is_valid():
        f = request.FILES['file']
        try:
            name = str(f)
            try:
                isnew = False
                c = Cert.objects.get(filename=name)
            except ObjectDoesNotExist:
                isnew = True
                c = Cert()

            c.frombuffer(f.read())
            if isnew:
                c.filename = name
            c.save()

            return render(request, 'success.html', {
                'vdict': c.verbose_dict(),
                'cert': c,
                'isnew': isnew
            })
        except crypto.Error as e:
            raise e

    return redirect('index')
Beispiel #15
0
def upload(request):
    c = all_page_infos(request)
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            ufile = request.FILES['file']
            short = request.POST['short']
            long_text = request.POST['long_text']
            tags = request.POST['tags']
            (path, written_bytes) = save_uploaded_file(ufile)
            logger.info("User '%s' uploaded file '%s' with title '%s', parsing it now.", request.user, os.path.basename(path), short[:20])
#            try:
            if written_bytes != ufile.size:
                return HttpResponse("Could not store the replay file. Please contact the administrator.")

            demofile = parse_demo_file.Parse_demo_file(path)
            demofile.check_magic()
            demofile.parse()

            try:
                replay = Replay.objects.get(gameID=demofile.header["gameID"])
                logger.info("Replay already existed: pk=%d gameID=%s", replay.pk, replay.gameID)
                return HttpResponse('Uploaded replay already exists: <a href="/replay/%s/">%s</a>'%(replay.gameID, replay.__unicode__()))
            except:
                shutil.move(path, settings.MEDIA_ROOT)
                replay = store_demofile_data(demofile, tags, settings.MEDIA_ROOT+os.path.basename(path), file.name, short, long_text, request.user)
                logger.info("New replay created: pk=%d gameID=%s", replay.pk, replay.gameID)
            return HttpResponseRedirect(replay.get_absolute_url())
#            except Exception, e:
#                return HttpResponse("The was a problem with the upload: %s<br/>Please retry or contact the administrator.<br/><br/><a href="/">Home</a>"%e)
    else:
        form = UploadFileForm()
    c['form'] = form
    return render_to_response('upload.html', c, context_instance=RequestContext(request))
Beispiel #16
0
def api_upload(request):
    if request.method == 'POST':
        picture = Picture()
        user = User.objects.get(email=request.POST['email'])
        picture.user = user
        form = UploadFileForm(request.POST, request.FILES, instance=picture)
        if form.is_valid():
            picture.picture = request.FILES['picture']
            if request.POST.has_key('gallery_id'):
                gallery = Gallery.objects.get(id=request.POST['gallery_id'],
                                              user=user)
                picture.gallery = gallery

            picture.picture.name = unidecode(picture.picture.name)
            picture.save()
            rotate_picture(picture)
            picture.update_thumb()

            if request.POST.has_key('description'):
                picture_description = PictureDescription(picture=picture)
                picture_description.text = request.POST['description']
                picture_description.save()

            response = {'status': 'OK'}
            response['data'] = serialize_picture(picture)
            return HttpResponse(json.dumps(response))

    return HttpResponse(content_200)
Beispiel #17
0
def xls(req):
    """通过XML 方式批量添加记录."""

    if req.session.get('username', None):
        #权限管理
        ld = permission()
        user = req.session['username']

        if user in ld:
            dt = datetime.now()
            if req.method == "POST":
                uf = UploadFileForm(req.POST, req.FILES)
                if uf.is_valid():
                    try:
                        mdelete()
                        f = uf.cleaned_data['file']
                        u = Upload(upload_dir=f)
                        u.save()
                    except Exception, e: 
                        logger.error(e)
                        sys.exit(1)
                    dir = select()
                    parserxls(dir)
                    return HttpResponse('ok')
            return render(req, 'xls.html')
        else:
            return HttpResponse('权限被解决')
Beispiel #18
0
def UploadExcelForm(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            wb = xlrd.open_workbook(filename = None,file_contents = request.FILES['excel'].read())
            ws = wb.sheet_by_index(0)
            for r in range(1,ws.nrows):
                megaNo = ws.cell(r,19).value
                sample = models.MedicineSampleInfo.objects.filter(sampleno=megaNo)
                mut_det_res = models.MedicineMutDetRes(id = sample[0].id,chr = ws.cell(r,0).value,start=ws.cell(r,1).value,ref=ws.cell(r,2).value,alt=ws.cell(r,3).value,gene=ws.cell(r,4).value,ref_seq=ws.cell(r,5).value,dna_ch=ws.cell(r,6).value,aa_ch=ws.cell(r,7).value,het=ws.cell(r,8).value,mut_type=ws.cell(r,9).value,disease=ws.cell(r,10).value,result=ws.cell(r,11).value,inher_type=ws.cell(r,12).value,info_gene=ws.cell(r,13).value,info_locus=ws.cell(r,14).value,info_disease=ws.cell(r,15).value,conclusion=ws.cell(r,16).value,ref_paper=ws.cell(r,17).value,ana_type=ws.cell(r,18).value,sam_num=ws.cell(r,19).value)
                mut_det_res.save()
                now = time.strftime('%Y%m%d-%H%M%S', time.localtime())

                try:
                    mut_res_get = models.MedicineMutRes.objects.get(id = sample[0].id)
                except:
                    print "数据库不存在此样本解读结果,执行插入操作"
                    mut_res = models.MedicineMutRes(id=sample[0].id, create_time=now, record_time=now, up_num=1)
                    mut_res.save()
                else:
                    print "数据库已存在此样本解读结果,执行更新操作"
                    up_num = mut_res_get.up_num + 1
                    models.MedicineMutRes.objects.filter(id=sample[0].id).update(record_time=now,up_num=up_num)

            return render_to_response('index/test.html',csrf(request).update({'mut_det_res': mut_det_res}))
    else:
        form = UploadFileForm()
    return render_to_response('index/parsemut.html',csrf(request).update({'from':form,}))
Beispiel #19
0
def upload(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            dest = form.cleaned_data['dest']
            handle_uploaded_file(dest, request.FILES['file'])
    return redirect('/')
Beispiel #20
0
def cloud_storage(request):

    print "-- cloud_storage:"

    if not request.user.is_authenticated():
        return HttpResponseRedirect("/")

    user = request.user
    profile = userprofile.objects.get(user=request.user)
    secret = profile.secret

    print request.user

    if request.method == "POST":
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            new_file = Files(file=request.FILES["file"])
            new_file.save()
            Uploaded_Files.objects.create(file=new_file, user=request.user)

    uploaded_files = Uploaded_Files.objects.filter(user=request.user).order_by("-pk")
    cloud_storage_menu_open = True

    # XXX batch sync files to the S3.....

    return render_to_response(
        "cloud_storage.html",
        {
            "cloud_storage_menu_open": cloud_storage_menu_open,
            "uploaded_files": uploaded_files,
            "user": user,
            "profile": profile,
        },
        context_instance=RequestContext(request),
    )
Beispiel #21
0
def upload(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            new_file = UploadFile(file=request.FILES['file'],
                                  user=request.user)
            print(new_file)
            new_file.save()

            return HttpResponseRedirect(reverse('upload'))
    else:
        form = UploadFileForm()
    uploads_root = settings.MEDIA_ROOT
    json_table, json_columns = f.excel_to_json(
        uploads_root + "/user_4/Data1_light.xlsx", 3)
    models = f.get_models_details()
    data = {
        'form': form,
        'table': json_table,
        'columns': json_columns,
        'table_models': models,
        'user': request.user.id
    }
    #data=RequestContext(request, data2)
    return render(request, 'app/OPEX/upload.html', data)
Beispiel #22
0
def uploadForm(user):
    """ Creates an UploadFileForm and pre-populates the school field
        With the user's school, if available
        is currently unused?
    """
    #print request.user.username
    user_profile = user.get_profile()
    if user_profile.school:
        print "The user has a school, so we will auto populate it"
        # This isn't the ideal way to override the field system. I would rather extend or replicate the existing UploadFileForm, but I am slightly unsure how to do that
        # Alternatively, I could figure out how to use the 'school' kv argument
        form = UploadFileForm(initial={'course': -1, 'school': user_profile.school.pk})
        form.fields['school'] = djangoforms.ModelChoiceField(
                queryset=School.objects.all(),
                widget=AutoCompleteWidget(
                    url='/schools',
                    initial_display=user_profile.school.name
                ),
                error_messages={'invalid_choice': 'Enter a valid school. Begin typing a school name to see available choices.',
                                'required': 'Enter a school.'},
            )
    else:
        # Provide bogus default school and course data to ensure
        # legitimate data is chosen
        form = UploadFileForm(initial={'course': -1, 'school': -1})
    return form
Beispiel #23
0
def publish(request):
    name = lName = request.session.get("name", False)
    if request.method == "POST":
        form = UploadFileForm(request.POST, request.FILES)
        # print form.errors
        if form.is_valid():
            handle_uploaded_file(request)
            title = request.POST.get("title")
            description = request.POST.get("description")
            price = request.POST.get("price")
            category = request.POST.get("category")
            # print request.POST.get('title')
            from datetime import date

            data = Data(
                title=title,
                description=description,
                price=price,
                category=category,
                creator=request.session.get("name"),
                createdDate=date.today(),
            )
            data.save()

            return HttpResponseRedirect("/market/mypublish/")
        else:
            return HttpResponse(form)
    else:
        form = UploadFileForm()
        return render_to_response(
            "dt/publish.html", {"form": form, "lName": lName}, context_instance=RequestContext(request)
        )
Beispiel #24
0
def create_test(request):
    username = auth_check(request)

    if request.method == "POST":
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            testfile = request.FILES["testfile"]
            new_file = UploadFile(testfile=request.FILES["testfile"])
            new_file.save()
            command = (
                "/usr/bin/python "
                + test_path
                + "/dashboard/testsrc/main.py "
                + test_path
                + "/../static/media/files/"
                + testfile.name
            )
            os.system(command)
            return HttpResponseRedirect(reverse("dashboard.views.create_test"))
    else:
        form = UploadFileForm()

    data = {"form": form}

    return render_to_response("create_test.html", locals(), context_instance=RequestContext(request))
Beispiel #25
0
def file_share(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            result = handle_uploaded_file(request.FILES['file'])
            if result:
                try:
                    file = File.objects.get(sha512=result['sha512'], user=request.user)
                    messages.error(request, 'You have already reported this file')
                    return HttpResponseRedirect('/file/%s' % file.id)
                except ObjectDoesNotExist:
                    file = form.save(commit=False)
                    file.uuid = uuid.uuid4().urn
                    file.user = request.user
                    file.filename = result['filename']
                    file.filesize = result['filesize']
                    file.md5 = result['md5']
                    file.sha1 = result['sha1']
                    file.sha256 = result['sha256']
                    file.sha512 = result['sha512']
                    file.save()
                    form.save_m2m()
                    for n in request.POST.getlist('nodes'):
                        node = PubSubNode.objects.get(node=int(n))
                        file.nodes.add(node)
                        xmpp.publish(node=node.node, payload=file.activity_fordrop_file())
                        if file.tags.all():
                            xmpp.publish(node.node, payload=file.activity_tags())

                    print json.dumps(file.activity_fordrop_file(), indent=4)
                    messages.success(request, "Sharing is caring, file successfully recieved!")
                    mail_body = '%s reported the same file as you, %s\n%s' % (file.user.profile.name, file.sha1, file.get_full_uri())
                    notify_by_mail(users=file.get_reporters(), subject='%s reported the same file as you' % file.user.profile.name, body=mail_body, obj=file)
    return HttpResponseRedirect('/file/%s' % file.id)
Beispiel #26
0
def cloud_storage(request):

	print '-- cloud_storage:'

	if not request.user.is_authenticated():
		return HttpResponseRedirect("/")

	user = request.user
	profile = userprofile.objects.get(user=request.user)
	secret = profile.secret

	print request.user

	if request.method == 'POST':
		form = UploadFileForm(request.POST, request.FILES)
		if form.is_valid():
			new_file = Files(file=request.FILES['file'])
			new_file.save()
			Uploaded_Files.objects.create(file=new_file,user=request.user)
  
	uploaded_files = Uploaded_Files.objects.filter(user=request.user).order_by('-pk')
	cloud_storage_menu_open = True

	# XXX batch sync files to the S3.....
	
	return render_to_response('cloud_storage.html', {'cloud_storage_menu_open':cloud_storage_menu_open,'uploaded_files':uploaded_files,'user':user,'profile':profile,}, context_instance=RequestContext(request))
Beispiel #27
0
def upload(request,foobar):
    if not request.user.is_authenticated():
        flag=1
        return render_to_response("notauthorized.html",locals(),context_instance=RequestContext(request))
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():	
            f = form.cleaned_data['files']
            f = request.FILES['files']	
            title = request.POST['title_with_extension']
            if foobar == "img":
                n = len(os.listdir(os.path.join(os.path.dirname(__file__),'..','downloads','gallery').replace('\\','/')))
                x = str(n+1)
                os.system("./manage.py collectstatic ") 
                dest = open(os.path.join(os.path.dirname(__file__),'..','downloads','gallery').replace('\\','/'+'/')+'/'+title,'wb+')
                #return HttpResponse(dest.name)
            elif foobar == "gen":
                n = len(os.listdir(os.path.join(os.path.dirname(__file__),'..','downloads','gen').replace('\\','/')))
                x = str(n+1)
                os.system("./manage.py collectstatic ") 
                dest = open(os.path.join(os.path.dirname(__file__),'..','downloads','gen').replace('\\','/'+'/')+'/'+title,'wb+')
	
            for chunk in request.FILES['files'].chunks():
                dest.write(chunk)
                os.system("./manage.py collectstatic ") 
            dest.close()
            f.close()
            os.system("./manage.py collectstatic ") 
            return HttpResponseRedirect('/corepage/')	
    else:
        form = UploadFileForm()
    return render_to_response('upload.html',{'form': form},context_instance=RequestContext(request))
Beispiel #28
0
def publish(request):
    name = lName = request.session.get('name', False)
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        #print form.errors
        if form.is_valid():
            handle_uploaded_file(request)
            title = request.POST.get('title')
            description = request.POST.get('description')
            price = request.POST.get('price')
            category = request.POST.get('category')
            #print request.POST.get('title')
            from datetime import date
            data = Data(title=title,
                        description=description,
                        price=price,
                        category=category,
                        creator=request.session.get('name'),
                        createdDate=date.today())
            data.save()

            return HttpResponseRedirect('/market/mypublish/')
        else:
            return HttpResponse(form)
    else:
        form = UploadFileForm()
        return render_to_response('dt/publish.html', {
            'form': form,
            'lName': lName
        },
                                  context_instance=RequestContext(request))
Beispiel #29
0
def upload_view(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            username = request.user.username
            outputfilename = handle_uploaded_file(request.FILES['myfilefield'],
                                                  username)
            userfiles, totalsize = getuserfiles('abahga2013', username)
            limit = 5000
            percentused = totalsize * 100 / limit
            return render_to_response('index.html', {
                'username': username,
                'userfiles': userfiles,
                'totalsize': totalsize,
                'limit': limit,
                'percentused': percentused
            },
                                      context_instance=RequestContext(request))
    else:
        form = UploadFileForm()
        username = request.user.username
    return render_to_response('upload.html', {
        'form': form,
        'username': username
    },
                              context_instance=RequestContext(request))
Beispiel #30
0
def uploader(request):
    result = 'Upload failed.'
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            result = handle_uploaded_file(request.FILES['file'])
    return render_to_response('patients/uploader.html', {'result': result})
Beispiel #31
0
def upload_image_for_match(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            #title
            tit = request.REQUEST.get("title", None)
            
            #Sensor
            lon = request.REQUEST.get('longitude', None)
            lat = request.REQUEST.get('latitude', None)
            azi = request.REQUEST.get("azimuth", None)
            pit = request.REQUEST.get("pitch", None)
            rol = request.REQUEST.get("roll", None)
            
            #Image
            image = Image(image_path = request.FILES['file'],
                          azimuth = azi,
                          pitch = pit,
                          roll = rol,
                          longitude = lon,
                          latitude = lat,
                          title = tit)
            image.save()
            
            '''match the image against the database'''
            name = image.match()
            obj = Object.objects.get(object_name = name)
            
            #wrap object_url and object_name as json and return
            return responseJson({'object_url':obj.img_path.name, 'object':obj.object_name})
            
        else:
            return fail()
    else:
        return fail()
Beispiel #32
0
def upload_file(request, pk):
    #获得一个任务的实例
    task_ins = get_object_or_404(Task, pk=pk)

    #如果获取到了POST的提交
    if request.method == 'POST':
        #获取form表单,request.FILES是存放文件的地方
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            #通过处理上传文件函数来获得返回值
            uf = handle_uploaded_file(request.FILES['file'])

            #获取上传文件的实例,并补充相应信息至数据库中
            upload_ins = Upload()
            #绑定相应的task id
            upload_ins.task_id = task_ins.id
            #记录相应的文件名
            upload_ins.upload_title = uf[0]
            #记录相应的上传路径
            upload_ins.upload_path = uf[1]
            #保存upload的实例
            upload_ins.save()
            return redirect('task_edit', pk=task_ins.id)
    else:
        form = UploadFileForm()

    #构建相应的context,传递至上传文件页面
    context = {
        'form': form,
        'page_title': '任务处理',
        'sub_title': '上传文件',

    }
    return render(request, 'upload.html', context)
Beispiel #33
0
def create_new_upload(request, template_name):
    """ Create new request (upload or paste) """
    errors = False
    if not is_valid_session(request):
        return HttpResponseRedirect(reverse('invalid_session'))

    if not request.session.get("preferences"):
        return HttpResponseRedirect(reverse('invalid_session'))

    if request.method == "POST":
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            #process
            filehandle, filename = mkstemp()
            os.close(filehandle)
            filehandle = open(filename, "w")
            chunks = ""
            if request.FILES.get('file'):
                for chunk in request.FILES['file'].chunks():
                    filehandle.write(chunk)
            else:
                filehandle.write(request.REQUEST.get('certificatefield'))
            filehandle.close()

            status, errors, fields = api_validate_csr(request.user.username,
                                                      filename)
            request.session['fields'] = fields
            if status:
                request.session['csrfilename'] = filename
                return HttpResponseRedirect(reverse('create_new_csr'))
            else:
                # handle cleanup
                os.remove(filename)
    else:
        form = UploadFileForm()

    preferences = request.session.get("preferences")
    if not preferences:
        errors = []
        errors.append("Invalid preferences")
    user = request.user.username
    employment = ""
    owner = ""
    ctype = preferences["computer_type"].name
    if preferences["employment"].name != "":
        employment = preferences["employment"].name + "-"
    if preferences["computer_owner"].name != "":
        owner = preferences["computer_owner"].name + "-"
    cn = "%s-%s%s%s" % (user, employment, owner, ctype)

    request.session.set_test_cookie()
    return render_to_response(template_name, {
        'form': form,
        'errors': errors,
        'preferences': preferences,
        'cn': cn
    },
                              context_instance=RequestContext(request))
Beispiel #34
0
def upload_file(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            handle_uploaded_file(request.FILES['file'],request.user)
            return HttpResponseRedirect(reverse("deck:deck_list") )
    else:
        form = UploadFileForm()
    return render_to_response('upload.html', RequestContext(request,{'form': form}))
Beispiel #35
0
def upload(request):

    if request.method == 'POST':
        upload_form = UploadFileForm(request.POST, request.FILES)
        if upload_form.is_valid():
            upload_form.handle_files()


    return HttpResponse('ok')
Beispiel #36
0
def upload_file(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            handle_uploaded_file(request.FILES['file'])
            return HttpResponseRedirect('success/')
    else:
        form = UploadFileForm()
    return render(request, 'plink/upload.html', {'form': form})
Beispiel #37
0
def upload_file(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            handle_uploaded_file(request.FILES['file'], request.user)
            return HttpResponseRedirect('/success/url/')
    else:
        form = UploadFileForm()
    return render_to_response('filetest.html', {'form': form})
Beispiel #38
0
def upload_file(request):
  if request.method == 'POST':
     form = UploadFileForm(request.POST, request.FILES)
     if form.is_valid():
        handle_uploaded_file(request.FILES['file'])
        return HttpResponse(json.dumps(stat))
  else:
     form = UploadFileForm()
  return render(request, 'upload.html', {'form': form}, context_instance=RequestContext(request))
Beispiel #39
0
def analyse(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            msg = create(request.FILES['msgfile'].read())
            return JsonResponse({"response": msg})
        return JsonResponse({"response": form.errors})
    else:
        return JsonResponse({"response": "Invalid Method"})
Beispiel #40
0
def upload(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            Raw_Input.handle_upload_file(request.FILES['file'])
            return HttpResponseRedirect('show')
    else:
        form=UploadFileForm()
    return render_to_response('upload.html',{'form': form},context_instance=RequestContext(request))
Beispiel #41
0
def upload(request):
	#if request.method == 'POST':
	form = UploadFileForm(request.POST, request.FILES)
	if form.is_valid() and request.user.is_authenticated:
		codefile = request.FILES['file']
		data = codefile.read().splitlines()
		index = 0
		error = 0
		if request.POST['type'] == '1':
			parent = ''
			for code in data:
				if code != 'NEWPARENT':
					try:
						b = Barcode.objects.get(code=code.upper())
						if parent == '':
							p = Barcode.objects.get(code=code.upper())
							parent = code
						else:
							i = Barcode.objects.get(code=code.upper())
							i.item.parent = p.item
							i.item.save()
					except ObjectDoesNotExist:
						error += 1
						data[index] = code + ' existiert nicht!'
				else:
					parent = ''
				index += 1
		elif request.POST['type'] == '2':
			business_area = models.BusinessArea.objects.get(name='ideell')
			category = models.Category.objects.get(name='Inventar')
			parent = models.Barcode.objects.get(code='H0000')
			tag = models.Tag.objects.get(name='Regale & Storage')

			for code in data:
				if code[0] == 'H' and len(code) == 5:
					try:
						b = Barcode.objects.get(code=code.upper())
						error += 1
						data[index] = code + ' existiert bereits'
					except ObjectDoesNotExist:
						name = 'Regalborte ' + code
						description = 'Borte im Hochregal \nReihe: ' + code[1] + '\nRegal: ' + code[2]
						i = models.Item(name=name, description=description, business_area=business_area, category=category, parent=parent.item, inUse=True)
						i.save()
						i.tag.add(tag)
						i.save()
						barcode = Barcode(code=code, item=i)
						barcode.save()
				else:
					data[index] = code + ' ist nicht im richtigen Format'
					error += 1
				index += 1
		return render(request, 'upload.html', {'form': form, 'data': data})
	else:
		form = UploadFileForm()
	return render(request, 'upload.html', {'form': form})
Beispiel #42
0
def ChangeAvatarView(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            instance = Account(file_field=request.FILES['file'])
            instance.save()
            return HttpResponseRedirect('/account/url/')
    else:
        form = UploadFileForm()
    return render_to_response('profile.html', {'form': form})
Beispiel #43
0
def uploader(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('index'))
    else:
        form = UploadFileForm()
    context = {'form': form}
    return render(request, 'uploader.html', context)
Beispiel #44
0
def upload(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            Raw_Input.handle_upload_file(request.FILES['file'])
            return HttpResponseRedirect('show')
    else:
        form = UploadFileForm()
    return render_to_response('upload.html', {'form': form},
                              context_instance=RequestContext(request))
Beispiel #45
0
def upload_file(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            fileName = handle_uploaded_file(request.FILES['file'])
            
            return HttpResponse('You file has been uploaded to %s ' % fileName)
    else:
        form = UploadFileForm()
    return render_to_response('testing/upload.html', {'form': form})
Beispiel #46
0
def prueba(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            newdoc = Usuario(us_img=request.FILES['file'])
            newdoc.save(form)
            return HttpResponseRedirect('/appella/')
    else:
        form = UploadFileForm()
    return render(request, 'index.html', {'form': form})
Beispiel #47
0
def prueba(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            newdoc = Usuario(us_img = request.FILES['file'])
            newdoc.save(form)
            return HttpResponseRedirect('/appella/')
    else:
        form = UploadFileForm()
    return render(request, 'index.html', {'form': form})
Beispiel #48
0
def upload_file(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            name = handle_uploaded_file(request.FILES['file'])
            server = Server.objects.all()
            return render_to_response('app_deploy.html', dict(servers=server, names=name),
                                      context_instance=RequestContext(request))
        else:
            server = Server.objects.all()
            return render_to_response('app_deploy.html', dict(servers=server), context_instance=RequestContext(request))
Beispiel #49
0
def upload_file(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            handle_uploaded_file(request.FILES['file'])
            return HttpResponseRedirect(
                'success/'
            )
    else:
        form = UploadFileForm()
    return render(request, 'plink/upload.html', {'form': form})
Beispiel #50
0
def process_file(request):
        if request.method == 'POST':
                form = UploadFileForm(request.POST, request.FILES)
                if form.is_valid():
                        data = handle_uploaded_file(request.FILES,request.session,request.user)
                        return HttpResponseRedirect(reverse('peep', args=[hash]))
        
        else:
                data = {'success':False,'error':"Processing failed on file"}

        return render_to_response('report.html', {'results': simplejson.dumps(data, cls=DjangoJSONEncoder)}, context_instance=RequestContext(request))
Beispiel #51
0
def import_opml(request):
    """

    @param request:
    @return:
    """
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            feed_manager.handle_opml(request)
    return HttpResponseRedirect('/')
Beispiel #52
0
def index(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            handle_uploaded_file(request.FILES['docfile'])

            return HttpResponseRedirect('', {'form': form})
    else:
        form = UploadFileForm()

    return render_to_response('index.html', {'form': form})
Beispiel #53
0
def add_photo(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            handle_uploaded_file(request.FILES['file'], request.POST["title"])
            return HttpResponseRedirect('/admin/')
    else:
        form = UploadFileForm()
    return render_to_response('upload.html', {'form': form},
                              context_instance=RequestContext(request))
    new_photo = Photos()
    return render_to_response("add.html")
Beispiel #54
0
def home(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            new_file = UploadFile(file = request.FILES['file'])
            new_file.save()

            return HttpResponseRedirect(reverse('main:home'))
    else:
        form = UploadFileForm()

    data = {'form': form}
    return render_to_response('main/index.html', data, context_instance=RequestContext(request))
Beispiel #55
0
def upload(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            #aqui va todo lo que tengo que hacer
            f = request.FILES['f']
            postulantes = f.readlines()
            for chunk in postulantes:
                chunk = chunk.split(';')

                hora = chunk[0].decode('iso-8859-1')
                fecha = chunk[1].decode('iso-8859-1')
                 
        
                try:
                    fecha = '%s-%s-%s %s'%(fecha.split('-')[2], fecha.split('-')[1], fecha.split('-')[0], hora) 

                except:
                    fecha = None 

                rut = chunk[2].decode('iso-8859-1')
                nombres = chunk[3].decode('iso-8859-1').title()
                apellidos = chunk[4].decode('iso-8859-1').title()
                domicilio=chunk[5].decode('iso-8859-1').title()
                comuna =chunk[6].decode('iso-8859-1').title()
                os10 =chunk[7].decode('iso-8859-1')
                if ('NO' or 'no' or 'No') in os10:
                    os10 = False
                elif ('SI' or 'SÍ' or 'sí' or 'si' or 'Sí' or 'Si') in os10:
                    os10 = True

                contratado = False 
              
                sexo =chunk[8].decode('iso-8859-1')
                medio =chunk[9].decode('iso-8859-1')
                cargo =chunk[10].decode('iso-8859-1')
                telefono =chunk[11].decode('iso-8859-1')
                observaciones = chunk[12].decode('iso-8859-1')
                reclutador =  chunk[13].decode('iso-8859-1')
                email = chunk[14].decode('iso-8859-1')
                postulante = Postulante(fecha=fecha, rut=rut, nombres=nombres, apellidos=apellidos, domicilio=domicilio, 
                comuna=comuna, os10=os10, sexo=sexo, medio=medio, cargo=cargo, telefono=telefono, 
                observaciones=observaciones, contratado=contratado, reclutador=reclutador, email=email)
                print rut
                postulante.save()

            return HttpResponse('OK') 
    else:
        form = UploadFileForm()

    return render(request, 'upload.html', {'form':form})
Beispiel #56
0
def home(request):
    if request.method == "POST":
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            file_information = handle_uploaded_file(
                request.FILES['file_upload'])
            return render(request, 'home.html', {
                'form': form,
                'file_information': file_information
            })
    else:
        form = UploadFileForm()

    return render(request, 'home.html', {'form': form})
Beispiel #57
0
def home(request):
    form = UploadFileForm(request.POST, request.FILES)
    if form.is_valid():
        filename = request.FILES['file']._get_name()
        path = ''
        textFile = image_file_to_string(
            '%s/%s' % (settings.MEDIA_ROOT, str(path) + str(filename)))
        request.session['textFile'] = textFile

        return HttpResponseRedirect(reverse('home'), locals())
    data = ""
    return render_to_response('index.html',
                              data,
                              context_instance=RequestContext(request))
Beispiel #58
0
def image_upload(request):
    if request.method == 'POST':
        formset = UploadFileForm(request.POST, request.FILES)
        if formset.is_valid():
            movie = Picture()
            movie.upload_content(request.FILES['file'])
            movie.put()
            Picture.get(movie.key())
            return redirect(image_list)
    else:
        formset = UploadFileForm()
    return render_to_response("image_upload.html", {
                                    "formset" : formset
                              }, context_instance=RequestContext(request))       
Beispiel #59
0
def survey_upload_db(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        #if form.is_valid():
        path = handle_uploaded_file(request.FILES.get('fileupload'))
        
        survey_id = request.POST.get('name')
        survey = Survey.objects.get(id=survey_id)

        if path and survey:
            conn = None
            try:
                conn = sqlite3.connect(path) #'/home/jose/Escritorio/geopaparazzi_20180115_185005.gpap')
                db_name = survey.name
                c = conn.cursor()
                for row in c.execute('SELECT _id, lon, lat, altim, ts, description, text, form, style, isdirty FROM notes;'):
                    print row
                    add_result_from_survey(request, db_name, row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7], row[8], row[9])
            except Exception as e:
                logger.exception(SYNCERROR_UPLOAD)
                return HttpResponseBadRequest(SYNCERROR_UPLOAD)
            finally:
                if conn != None:
                    conn.close()
                os.remove(path)
                
        return JsonResponse({'result': 'OK'})
    
    else:
        form = UploadFileForm()
        
        survey_list = Survey.objects.all().order_by('id')
        surveys = []
        
        admin_group = UserGroup.objects.get(name__exact='admin')
        sug = UserGroupUser.objects.filter(user_group_id=admin_group.id,user_id=request.user.id).count()
        if sug > 0:
            # Es admin
            for survey in survey_list:
                surveys.append(survey)
        else:
            ugus = UserGroupUser.objects.filter(user_id=request.user.id)
            for ugu in ugus:
                for survey in survey_list:
                    sug = SurveyWriteGroup.objects.filter(user_group_id=ugu.user_group.id,survey_id=survey.id).count()
                    if sug > 0:
                        surveys.append(survey)
                
                
        return render(request, 'survey_upload.html', {'form': form,  'surveys': surveys})