Esempio n. 1
0
def upload_files(request):

    # The assumption here is that jQuery File Upload
    # has been configured to send files one at a time.
    # If multiple files can be uploaded simulatenously,
    if not request.user.is_authenticated():
        Uploadresponse(request, {})

    message_id = request.POST.get('message', '-1')
    message = get_element(Message, int(message_id))
    if message == False:
        return UploadResponse(request, {})

    file = upload_receive(request)
    instance = File(file=file, name=file.name, message=message)
    instance.save()
    basename = os.path.basename(instance.file.path)
    file_dict = {
        'name': basename,
        'size': file.size,
        'url': settings.MEDIA_URL + basename,
        'thumbnailUrl': settings.MEDIA_URL + basename,
        'delete_url': reverse('jfu_delete', kwargs={'pk': instance.pk}),
        'delete_type': 'POST',
    }

    return UploadResponse(request, file_dict)
Esempio n. 2
0
def upload(request):
    """JFU function to handle uplaods
    The assumption here is that jQuery File Upload
    has been configured to send files one at a time.
    If multiple files can be uploaded simulatenously,
    'file' may be a list of files.
    """
    my_file = upload_receive(request)
    #instance = YourUploadModel( file_field = file )
    basename = my_file.name
    tfile = tempfile.NamedTemporaryFile("w", delete=False)
    tfile.write(my_file.read())
    arg_list[basename] = tfile.name
    #basename = os.path.basename( instance.file_field.file.name )
    file_dict = {
        'name': basename,
        'size': my_file.size,
        #instance.file_field.file.size,
        # The assumption is that file_field is a FileField that saves to
        # the 'media' directory.
        'url': settings.MEDIA_URL + basename,
        'thumbnail_url': settings.MEDIA_URL + basename,
        'delete_type': 'POST',
    }
    return UploadResponse(request, file_dict)
Esempio n. 3
0
def uploadVerify(request):

    # The assumption here is that jQuery File Upload
    # has been configured to send files one at a time.
    # If multiple files can be uploaded simulatenously,
    # 'file' may be a list of files.
    print("request.user")
    file = upload_receive(request)
    # return
    # feedbackObj = feedback.objects.create(userId = request.user)
    # feedbackObj.save()
    # print(feedbackObj)
    instance = agent_files(fileUpload=file, userId=request.user)
    instance.save()

    basename = os.path.basename(instance.fileUpload.path)

    file_dict = {
        'name': basename,
        'size': file.size,
        'url': settings.MEDIA_URL + basename,
        'thumbnailUrl': settings.MEDIA_URL + basename,

        # 'deleteUrl': reverse('jfu_delete', kwargs = { 'pk': instance.pk }),
        # 'deleteType': 'POST',
    }

    return UploadResponse(request, file_dict)
Esempio n. 4
0
File: views.py Progetto: StuJ/rua-1
def upload(request, book_id, type_to_handle):
    book = get_object_or_404(core_models.Book, pk=book_id, owner=request.user)
    _file = upload_receive(request)
    new_file = handle_file(_file, book, type_to_handle, request.user)

    if new_file:
        file_dict = {
            'name':
            new_file.uuid_filename,
            'size':
            _file.size,
            'deleteUrl':
            reverse('jfu_delete',
                    kwargs={
                        'book_id': book_id,
                        'file_pk': new_file.pk
                    }),
            'url':
            reverse('serve_file',
                    kwargs={
                        'submission_id': book_id,
                        'file_id': new_file.pk
                    }),
            'deleteType':
            'POST',
            'ruaId':
            new_file.pk,
            'original_name':
            new_file.original_filename,
        }

        return UploadResponse(request, file_dict)
    return HttpResponse('No file')
def upload(request):
	task_id = request.POST.get('task_id', None)
	task = Task.objects.get(pk=int(task_id))
	
	if ACL.canUpdateTask(request.user, task):
		if task.hasPermissions(request.user):
			file_dict = {'task_id': task_id}

			if task_id!=None:
				file = upload_receive( request )

				task = Task.objects.get(pk=int(task_id))
				instance = TaskAttachment( task_attachment_file = file, task=task )
				instance.save()

				basename = os.path.basename( instance.task_attachment_file.path )

				file_dict = {
					'name' : basename,
					'size' : instance.task_attachment_file.size,

					'url': settings.MEDIA_URL + str(instance.task_attachment_file),
					'thumbnailUrl': '/static/file_thumb.png',

					'deleteUrl': reverse('jfu_delete', kwargs = { 'pk': instance.pk }),
					'deleteType': 'POST',
				}
		else:
			file_dict = {}
	else:
		raise Exception('Permission denied')

	return UploadResponse( request, file_dict )
Esempio n. 6
0
def jfu_upload(request):
    event = get_object_or_404(Event, id=request.session['event_id'])
    profile = get_object_or_404(Profile, id=request.session['profile_id'])

    uploaded_file = upload_receive(request)

    instance = Photo(
        photo=uploaded_file,
        event=event,
        profile=profile,
    )
    instance.save()

    basename = os.path.basename(instance.photo.path)

    file_dict = {
        'name': basename,
        'size': uploaded_file.size,
        'url': instance.photo.url,
        'thumbnailUrl': instance.get_thumbnail().url,

        #'deleteUrl': reverse('jfu_delete', kwargs={'pk': instance.pk}),
        #'deleteType': 'POST',
    }

    return UploadResponse(request, file_dict)
Esempio n. 7
0
def upload_author(request, assignment_type, assignment_id, type_to_handle):
    assignment = logic.get_assignment(assignment_type, assignment_id)
    book = assignment.book
    _file = upload_receive(request)
    new_file = handle_file(_file, book, type_to_handle, request.user)

    if new_file:
        file_dict = {
            'name': new_file.uuid_filename,
            'size': _file.size,
            'deleteUrl': reverse(
                'assignment_jfu_delete',
                kwargs={
                    'assignment_type': assignment_type,
                    'assignment_id': assignment_id,
                    'file_pk': new_file.pk,
                }
            ),
            'url': reverse(
                'serve_file',
                kwargs={'submission_id': book.id, 'file_id': new_file.pk}
            ),
            'deleteType': 'POST',
            'ruaId': new_file.pk,
            'original_name': new_file.original_filename,
        }
        _assignment = logic.add_file(assignment, new_file, True)

        return UploadResponse(request, file_dict)

    return HttpResponse('No file')
Esempio n. 8
0
    def post(self, request, *args, **kwargs):
        '''Verify uuid and call model.objects.record_upload().'''
        if 'mrsrequest_uuid' not in kwargs:
            return http.HttpResponseBadRequest('Nous avons perdu le UUID')
        mrsrequest_uuid = kwargs['mrsrequest_uuid']

        if not MRSRequest(id=mrsrequest_uuid).is_allowed(request):
            return http.HttpResponseBadRequest('Token de formulaire invalide')

        if not request.FILES:
            return http.HttpResponseBadRequest('Pas de fichier reçu')

        # need to reverse engineer some action now to finish specs because our
        # mock object doesn't simulate all attributes

        files = []
        for key, upload in request.FILES.items():
            mimetype = mimetypes.guess_type(upload.name)[0]
            if mimetype not in DEFAULT_MIME_TYPES:
                return http.HttpResponseBadRequest(
                    'Type de fichier non accepté')
            if upload.size > MAX_FILE_SIZE:
                return http.HttpResponseBadRequest('Fichier trop volumineux')

            record = self.model.objects.record_upload(mrsrequest_uuid, upload)
            files.append(
                dict(
                    name=record.filename,
                    url=record.get_download_url(),
                    thumbnailUrl=record.get_download_url(),
                    deleteUrl=record.get_delete_url(),
                    deleteType='DELETE',
                ))

        return UploadResponse(request, files)
Esempio n. 9
0
def upload(request):

    # The assumption here is that jQuery File Upload
    # has been configured to send files one at a time.
    # If multiple files can be uploaded simulatenously,
    # 'file' may be a list of files.
    imagen = upload_receive(request)

    usertests = UserTests.objects.get(user_id=request.user.id)
    instance = Image(image=imagen, uploader=usertests)
    instance.save()

    basename = os.path.basename(instance.image.path)
    namepath = "media/" + basename

    file_dict = {
        'name': basename,
        'size': imagen.size,
        'id': instance.pk,
        'url': settings.MEDIA_URL + namepath,
        'thumbnailUrl': "/" + settings.MEDIA_URL + namepath,
        'deleteUrl': reverse('testsforall:jfu_delete',
                             kwargs={'pk': instance.pk}),
        'deleteType': 'POST',
    }

    return UploadResponse(request, file_dict)
Esempio n. 10
0
File: views.py Progetto: siadyhr/web
def upload(request):
    file = upload_receive(request)
    album = Album.objects.get(id=int(request.POST['object_id']))
    ext = os.path.splitext(file.name)[1].lower()

    if ext in (".png", ".gif", ".jpg", ".jpeg"):
        instance = Image(file=file, album=album)
    elif ext in (".mp3"):
        instance = GenericFile(file=file, album=album)
        instance.type = BaseMedia.AUDIO
    elif ext in (".mp4"):
        instance = GenericFile(file=file, album=album)
        instance.type = BaseMedia.VIDEO
    else:
        instance = GenericFile(file=file, album=album)
        instance.type = BaseMedia.OTHER

    try:
        instance.full_clean()
        instance.save()
    except ValidationError as exn:
        try:
            error = ' '.join('%s: %s' % (k, v)
                             for k, vs in exn.message_dict.items() for v in vs)
        except AttributeError:
            error = ' '.join(exn.messages)

        jfu_msg = {
            'name': file.name,
            'size': file.size,
            'error': error,
        }
        return UploadResponse(request, jfu_msg)

    jfu_msg = {
        'name': os.path.basename(instance.file.path),
        'size': file.size,
        'url': instance.file.url,
    }
    return UploadResponse(request, jfu_msg)
Esempio n. 11
0
def upload(request):
    file = upload_receive(request)
    instance = Photo(file=file)
    instance.save()

    basename = os.path.basename(instance.file.file.name)
    file_dict = {
        'name': basename,
        'size': instance.file.file.size,
        'url': settings.MEDIA_URL + basename,
        'thumbnail_url': settings.MEDIA_URL + basename,
        'delete_url': reverse('jfu_delete', kwargs={'pk': instance.pk}),
        'delete_type': 'POST',
    }

    return UploadResponse(request, file_dict)
Esempio n. 12
0
def upload( request ):
    try:
      username = request.session['DukUser']
      user = DukUser.objects.get(username = username)
      ui = user.usermovie_set.all()[0]
    except:
      user = None

    url =  request.get_full_path()
    code = url.split('?')[1]

    m = Movie.objects.get(code = code)
    f = upload_receive(request)
    f.name = code+"_"+f.name
    
    v = Video(file_field = f)

    if user:
      v.uploader = user

    v.movie = m
    v.save()

    path, ext = os.path.splitext(v.file_field.name)
    path = "media/" + path

    #subprocess.call( ["ffmpeg", "-i" , path + ext, path + ".webm"])

    basename = os.path.basename( v.file_field.file.name )
    file_dict = {
        'name' : basename,
        'size' : v.file_field.file.size,

        # The assumption is that file_field is a FileField that saves to
        # the 'media' directory.
        'url': settings.MEDIA_URL + basename,
        'thumbnail_url': settings.MEDIA_URL + basename,


        'delete_url': reverse('jfu_delete', kwargs = { 'pk': v.pk }),
        'delete_type': 'POST',
    }

    return UploadResponse( request, file_dict )
Esempio n. 13
0
def upload( request ):
    video = upload_receive( request )

    instance = Video( video = video )
    instance.save()

    basename = os.path.basename( instance.video.path )
    
    file_dict = {
        'name' : basename,
        'size' : video.size,

        'url': settings.MEDIA_URL + basename,
        'thumbnailUrl': settings.MEDIA_URL + basename,

        'deleteUrl': reverse('jfu_delete', kwargs = { 'pk': instance.pk }),
        'deleteType': 'POST',
    }

    return UploadResponse( request, file_dict )
Esempio n. 14
0
def upload(request):
    file = upload_receive(request)

    instance = Dump(file=file,
                    name=file.name,
                    timestamp=datetime.datetime.now())
    instance.save()

    basename = os.path.basename(instance.file.path)

    file_dict = {
        'name': basename,
        'size': file.size,
        'url': settings.MEDIA_URL + basename,
        'thumbnailUrl': settings.MEDIA_URL + basename,
        'deleteUrl': reverse('jfu_delete', kwargs={'pk': instance.pk}),
        'deleteType': 'POST',
    }

    return UploadResponse(request, file_dict)
Esempio n. 15
0
def upload(request):
    file = upload_receive(request)

    #para doctores multiples se tiene que cambiar la consulta de atenciones
    instance = ArchivosAdjuntos(file=file,
                                atenciones=Atenciones.objects.last())
    instance.save()

    basename = os.path.basename(instance.file.path)

    file_dict = {
        'name': basename,
        'size': file.size,
        'url': settings.MEDIA_URL + basename,
        'thumbnailUrl': settings.MEDIA_URL + basename,
        'deleteUrl': reverse('jfu_delete', kwargs={'pk': instance.pk}),
        'deleteType': 'POST',
    }

    return UploadResponse(request, file_dict)
Esempio n. 16
0
def upload(request):

    image = upload_receive(request)
    size = image.size

    model = Image(image=image, resized_image=image)
    basename = os.path.basename(model.image.path)
    model.original_name = os.path.basename(model.image.path)
    model.size = Image.human_size(size)
    model.save()

    file_dict = {
        'name': basename,
        'size': size,
        'url': MEDIA_URL + str(model.image),
        'thumbnailUrl': MEDIA_URL + str(model.resized_image),
        'deleteUrl': reverse('images:upload_delete', kwargs={'pk': model.pk}),
        'deleteType': 'POST',
    }

    return UploadResponse(request, file_dict)
Esempio n. 17
0
def upload(request):
    path = request.POST.get('path', '/')

    files = upload_receive(request)
    if not isinstance(files, list): files = [files]
    data = files[0]
    filename = os.path.join(path, str(data))

    storage = AVAILABLE_STORAGES.get(request.user)
    storage.put_file_contents(filename, data)
    fileinfo = storage.file_info(filename)

    file_dict = {
        'name': fileinfo.filename,
        'size': sizeof_fmt(fileinfo.size),
        'thumbnail_url': fileinfo.small_thumb,
        'url': fileinfo.open_link,
        'delete':
        '',  #'delete_url': reverse('jfu_delete', kwargs = {'filename': str(data) }),
        'delete_type': 'POST',
    }
    return UploadResponse(request, file_dict)
Esempio n. 18
0
def jfu_upload(request):

    key = request.GET.get('key')

    file = upload_receive(request)

    instance = AdPhoto(file=file)
    instance.save()

    basename = os.path.basename(instance.file.path)

    file_dict = {
        'name':
        basename,
        'size':
        file.size,
        'url':
        '%s/%s' % (
            settings.MEDIA_URL,
            instance.file,
        ),
        'thumbnailUrl':
        '%s/%s' % (
            settings.MEDIA_URL,
            instance.file,
        ),
        'deleteUrl':
        reverse('pca_jfu_delete', kwargs={'pk': instance.pk}) + '?key=' + key,
        'deleteType':
        'POST',
    }

    # Can't do it in one line !
    file_list = request.session['pca_files_%s' % (key, )]
    file_list.append(instance.pk)
    request.session['pca_files_%s' % (key, )] = file_list

    return UploadResponse(request, file_dict)
Esempio n. 19
0
def multiple_document_upload(request):
    """
    Handles the mutiple document upload feature
    :param request: WSGI Request
    :return:
    """
    if request.method == 'POST':

        file = upload_receive(request)

        name = str(file)

        try:
            m = DOCUMENT_NAMING_PATTERN.match(name)
            if not m:
                raise FormatError(
                    f"File name does not match convention. e.g NE_G0123X_1_DMP.docx"
                )

            grant_ref = m.group('grant_ref').replace('_', '/')

            file_type = m.group('doc_type').lower()
            if file_type != 'dmp':
                file_type = 'support'

            document = Document(upload=file)

            document.grant = Grant.objects.get(grant_ref=grant_ref)
            document.type = file_type
            document.save()
        except ValidationError:
            response = HttpResponse(status=400)
            response.reason_phrase = 'File already uploaded'

        except FormatError as exc:
            response = HttpResponse(status=400)
            response.reason_phrase = f'{exc}'

        except ObjectDoesNotExist:
            response = HttpResponse(status=404)
            response.reason_phrase = f'Grant ref: {grant_ref} not found'

        else:

            file_dict = {
                'name': file.name,
                'size': file.size,
                'url': document.upload.url,
                'deleteUrl': reverse('delete_file', kwargs={'pk':
                                                            document.pk}),
                'deleteType': 'POST',
            }
            response = UploadResponse(request, file_dict)

        return response
    else:
        form = datamad_forms.MultipleDocumentUploadForm()
    return render(request, 'datamad2/multiple_document_upload.html', {
        'form': form,
        'JQ_OPEN': '{%',
        'JQ_CLOSE': '%}'
    })
Esempio n. 20
0
def upload(request):
    # The assumption here is that jQuery File Upload
    # has been configured to send files one at a time.
    # If multiple files can be uploaded simulatenously,
    # 'file' may be a list of files.
    issue = get_object_or_404(Issue, id=int(request.POST['issue_id']))

    if 'update_issue' in request.POST:
        event_value = {'files': [], 'comment': '', 'compilers': []}
        event_value['comment'] = request.POST['comment']
        file_counter = 0

        for field, value in dict(request.POST).iteritems():
            if 'compiler' in field:
                pk = int(field[13:])
                file = File.objects.get(pk=pk)
                compiler_id = value
                event_value['files'].append(file.file)
                event_value['compilers'].append(compiler_id)

            if 'pk' in field:
                pk = int(value[0])
                file = File.objects.get(pk=pk)
                file_counter += 1
                event_value['files'].append(file.file)
                event_value['compilers'].append(None)

        if not (issue.task.one_file_upload and file_counter > 1):
            event = issue.set_byname('comment', event_value, request.user)

            if not (issue.task.course.easyCI is None or issue.task.course.easyCI == ''):
                print(issue.task.course.easyCI)
                files = []
                for sent_file in event_value['files']:
                    print(request.build_absolute_uri(sent_file.url))
                    files.append(request.build_absolute_uri(sent_file.url))

                if len(files) != 0:
                    check_request_dict = {
                        'files': files,
                        'course_id': issue.task.course_id,
                        'title': issue.task.get_title(),
                        'issue_id': issue.id,
                        'event': {
                            'id': event.id,
                            'timestamp': event.timestamp.isoformat()
                        }
                    }
                    requests.post(issue.task.course.easyCI + "/api/add_task", json=check_request_dict)

        return redirect(issue_page, issue_id=int(request.POST['issue_id']))

    file = upload_receive(request)
    field = get_object_or_404(IssueField, name='file')
    event = Event.objects.create(issue_id=issue.id, field=field)

    problem_compilers = []
    chosen_compiler = None
    send_to_contest = False

    if issue.task.contest_integrated:
        problem_compilers = get_problem_compilers(issue.task.problem_id, issue.task.contest_id)
        for ext in settings.CONTEST_EXTENSIONS:
            filename, extension = os.path.splitext(file.name)
            if ext == extension:
                send_to_contest = True
                if not problem_compilers:
                    chosen_compiler = settings.CONTEST_EXTENSIONS[ext]
                if settings.CONTEST_EXTENSIONS[ext] in problem_compilers:
                    chosen_compiler = settings.CONTEST_EXTENSIONS[ext]
                    problem_compilers.remove(chosen_compiler)

    one_file_upload = False
    if issue.task.one_file_upload:
        filename, extension = os.path.splitext(file.name)
        file.name = 'upload' + extension
        one_file_upload = True
    else:
        file.name = unidecode(file.name)

    instance = File(file=file, event=event)
    instance.save()

    basename = instance.filename()

    file_dict = {
        'name': basename,
        'size': file.size,

        'url': instance.file.url,
        'thumbnailUrl': instance.file.url,

        'delete_url': reverse('jfu_delete', kwargs={'pk': instance.pk}),
        'delete_type': 'POST',

        'problem_compilers': problem_compilers,
        'chosen_compiler': chosen_compiler,
        'pk': instance.pk,
        'send_to_contest': send_to_contest,

        'one_file_upload': one_file_upload,
    }

    return UploadResponse(request, file_dict)