Example #1
0
def reader(request):
    if request.method == "POST":
        json = {}
        file = request.FILES['file']
        pdf = pdftotext.PDF(file)
        # mystring = pdf[3].replace('\n', ' ').replace('\r', '')
        # print(mystring.replace('\t', " ")[53:])
        try:
            previous_book = db.books.find().sort(
                '$natural', pymongo.DESCENDING).limit(-1).next()

        except:
            previous_book = {"id": 0}

        previous_book1 = previous_book["id"] + 1

        #storing the file in a fold

        form = UploadForm(request.POST, request.FILES)
        print("outsite")
        if form.is_valid():
            print("done")
            newdoc = Uploads(file=request.FILES['file'],
                             bookid=previous_book1,
                             filename=request.FILES['file'].name)
            newdoc.save()
        else:
            return render(request, 'home.html', {'form': form})

        db.books.insert({
            "id": previous_book1,
            "book_name": "nptel",
            "pages": len(pdf)
        })
        try:
            previous_page = db.pages.find().sort(
                '$natural', pymongo.DESCENDING).limit(-1).next()
        except:
            previous_page = {"id": 0}

        pid = previous_page["id"]
        for index, page in enumerate(pdf):

            pid += 1
            files = page.replace('\n', ' ').replace('\r', '')
            db.pages.insert({
                "id": pid,
                "book_id": previous_book1,
                "text": files,
                "page_number": index
            })

        return redirect('questions', book_id=previous_book1)

    form = UploadForm()
    return render(request, 'home.html', {'form': form})
Example #2
0
 def upload(self):
     if not current_user.is_authenticated:
         return redirect(url_for('login'))
     
     if request.method == 'GET':
         return self.render('admin/upload.html', form=UploadForm())
     
     if request.method == 'POST':
         form = UploadForm(request.form)
         file_storage = request.files['file']
         grade = form.grade
         df = get_df(file_storage)
         html_table = df.head().to_html(classes=['table', 'table-hover', 'table-condensed', 'table-bordered'], border=0, index=False)
         subjects = get_subjects(df)
         return self.render('admin/uploaded.html', df=html_table)
Example #3
0
def eyewitness():
    form = UploadForm()

    if form.validate_on_submit():

        f = form.upload.data
        if not allowed_video_file(f.filename):
            flash("Invalid file type")
            return redirect(url_for('eyewitness'))

        filename = secure_filename(f.filename)
        f.save(os.path.join(app.config['UPLOAD_FOLDER'], 'video', filename))

        video = Video(title=form.title.data, description=form.description.data, filename=filename, author=current_user)
        db.session.add(video)
        db.session.commit()
        flash("Video successfully uploaded.")
        return redirect(url_for('eyewitness'))

    page = request.args.get('page', 1, type=int)
    videos = current_user.followed_videos().paginate(
        page, app.config['VIDEOS_PER_PAGE'], False)

    next_url = url_for('eyewitness', page=videos.next_num) if videos.has_next else None
    prev_url = url_for('eyewitness', page=videos.prev_num) if videos.has_prev else None

    return render_template('eyewitness.html', title="The Frontlines", form=form, videos=videos.items, next_url=next_url, prev_url=prev_url)
Example #4
0
def upload():

    filefolder = UPLOAD_FOLDER

    form = UploadForm()

    if not session.get('logged_in'):
        abort(401)

    # Instantiate your form class

    # Validate file upload on submit
    if request.method == 'POST':
        # Get file data and save to your uploads folder
        if form.validate_on_submit():
            file = request.files.get('file')

            filename = secure_filename(form.upload.data.filename)
            form.upload.data.save(os.path.join(filefolder, filename))
            flash('File Saved', 'success')
            return redirect(url_for('home'))

    if request.method == 'GET':

        return render_template('upload.html', form=form)

    return render_template('upload.html', form=form)
Example #5
0
def upload_spreadsheet():
    if current_user.is_authenticated:
        form = UploadForm()
        if form.validate_on_submit():
            ppp_spreadsheet_filepath = Path("app", app.config["UPLOAD_FOLDER"], form.ppp_spreadsheet.data.filename)
            xr_spreadsheet_filepath = Path("app", app.config["UPLOAD_FOLDER"], form.xr_spreadsheet.data.filename)
            countries_json_filepath = Path("app", app.config["UPLOAD_FOLDER"], form.countries_json.data.filename)
            
            form.ppp_spreadsheet.data.save(ppp_spreadsheet_filepath)
            form.xr_spreadsheet.data.save(xr_spreadsheet_filepath)
            form.countries_json.data.save(countries_json_filepath)

            try:
                extract_data(ppp_spreadsheet_filepath, xr_spreadsheet_filepath, countries_json_filepath)
                db.session.commit()
                success = True
            except Exception as e:
                print(e)
                db.session.rollback()
                flash("Failed to extract data from uploaded files. Please ensure the files have the appropriate structure.", 'danger')
                success = False            
            
            remove(ppp_spreadsheet_filepath)
            remove(xr_spreadsheet_filepath)
            remove(countries_json_filepath)
            
            if success:
                flash("Successfully extracted data from uploaded files.", 'success')
                return redirect(url_for('calculator'))
        return render_template('upload.html', form=form)
    return redirect(url_for('calculator'))
Example #6
0
def upload():
    filefolder = UPLOAD_FOLDER
    # Instantiate your form class
    # Validate file upload on submit
    form = UploadForm()
    if request.method == 'POST' and form.validate_on_submit():
        # Get file data and save to your uploads folder
        file = request.files.get('file')

        description = form.description.data
        #print(description)
        filename = secure_filename(form.photo.data.filename)
        #print(filename)
        form.photo.data.save(os.path.join(filefolder, filename))
        tasks = [{
            'message': 'File Upload Successful',
            'filename': filename,
            'description': description
        }]
        status = "fine"

        #some var from flask

        return jsonify(upload=tasks, state=status)

    else:
        errors = form_errors(form)
        status = "wrong"
        return jsonify(error=errors, state=status)
    """else:
Example #7
0
def upload():
    if not session.get('logged_in'):
        abort(401)

    # Instantiate your form class
    form = UploadForm()
    # Validate file upload on submit
    if request.method == 'POST' and form.validate_on_submit():
        # Get file data and save to your uploads folder
        image = form.image.data
        filename = secure_filename(image.filename)
        image.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        flash('File Saved', 'success')
        return redirect(url_for('home'))
    flash_errors(form)
    return render_template('upload.html', form=UploadForm())
Example #8
0
def icon():
    form = UploadForm()
    if form.validate_on_submit():
        # 提取后缀
        suffix = os.path.splitext(form.icon.data.filename)[1]
        # 生成随机文件名
        filename = random_string() + suffix
        # 保存上传文件
        photos.save(form.icon.data, name=filename)
        # 拼接完整文件路径名
        pathname = os.path.join(current_app.config['UPLOADED_PHOTOS_DEST'], filename)
        # 生成缩略图
        img = Image.open(pathname)
        # 设置尺寸
        img.thumbnail((64, 64))
        # 覆盖保存图片
        img.save(pathname)
        # 删除原来的头像(默认头像除外)
        if current_user.icon != 'default.jpg':
            os.remove(os.path.join(current_app.config['UPLOADED_PHOTOS_DEST'], current_user.icon))
        # 保存到数据库
        current_user.icon = filename
        db.session.add(current_user)
    # 获取url
    img_url = url_for('static', filename='upload/'+current_user.icon)
    return render_template('user/icon.html', form=form, img_url=img_url)
Example #9
0
def index():
    form = UploadForm()
    if request.method == 'POST' and form.validate_on_submit():
        input_file = request.files['input_file']
        print("HALLO")
    else:
        return render_template('index.html', title='Home', form=form)
def modify_form(item_id):
    form = UploadForm()
    item = Item.query.filter_by(id=item_id).first()
    if form.validate_on_submit():
        if form.pic.data:
            suffix = os.path.splitext(form.pic.data.filename)[1]
            filename = random_string() + suffix
            photos.save(form.pic.data, name=filename)
            item.pic = filename
        category = Category.query.filter_by(name=form.category.data).first()
        item.item_name = form.item_name.data
        item.status = form.status.data
        item.location = form.location.data
        item.time = form.time.data
        item.category_id = category.id
        item.description = form.description.data
        change = Change(changer_id=current_user.id,
                        method='modify',
                        item_id=item.id,
                        item_name=item.item_name,
                        content='change a ' + form.status.data +
                        ' item named ' + form.item_name.data)
        db.session.add(change)
        if form.store_location.data != 'No selection':
            storage = Storage.query.filter_by(
                location_name=form.store_location.data).first()
            item.store_location_id = storage.id
        db.session.commit()
        return 'success'
    return render_template('upload_form.html',
                           form=form,
                           current_user=current_user)
def modify(item_id):
    item = Item.query.filter_by(id=item_id).first()
    form = UploadForm()
    return render_template('modify_item.html',
                           form=form,
                           item=item,
                           current_user=current_user)
Example #12
0
def upload():
    """Render the website's upload page."""
    uploadform = UploadForm()

    if request.method == 'POST':
        if uploadform.validate_on_submit():

            description = uploadform.description.data
            photo = uploadform.photo.data

            filename = secure_filename(photo.filename)
            photo.save(os.path.join(
                app.config['UPLOAD_FOLDER'], filename
            ))

            formdata = {
                "message": "File Upload Successful",
                "filename": filename,
                "description": description
            }
            return jsonify(formdata=formdata)
        else:
            errordata = {
                "errors": form_errors(uploadform)
            }
            return jsonify(errordata=errordata)
Example #13
0
def upload():
    if not current_user.admin:
        return redirect(url_for('index'))
    form = UploadForm()
    # f = form.quizjsondata.data = form.quizjson.data
    if form.validate_on_submit():
        #f = form.quizjson.data
        #content = f.read()

        #print(f.filename)
        #print(content)

        #filename = secure_filename(f.filename)
        #f.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))

        #data = json.loads(content)
        #q_id = Quiz.query.order_by(Quiz.id.desc()).first()
        #if not q_id:
        #    q_id = 1
        #else:
        #    q_id += 1
        #quiz = Quiz(id=q_id, name=data['name'], created_by=current_user)
        #db.session.add(quiz)
        #ques = data['questions']
        #for que in ques:
        #    question = Question(quiz_id=q_id, ques_type=que['type'], question=que['question'], options=que['options'], correct_answer=que['correct'], marks=que['marks'])
        #    db.session.add(question)
        #db.session.commit()
        return redirect(url_for('index'))
    return render_template('upload.html', form=form)
Example #14
0
def upload():
    form = UploadForm()
    if form.validate_on_submit():
        f = form.file.data
        file_name = f.filename
        file_name = secure_filename(f.filename)  # Real filename
        file = File.query.filter_by(file_name=file_name).first()
        if file in File.query.all():
            flash('Ya existe un archivo con ese nombre.')
            return render_template('500.html'), 500
        upload_folder = app.config['UPLOAD_FOLDER']
        if os.path.isdir(upload_folder) == False:
            os.makedirs(upload_folder)
        file_path = os.path.join(upload_folder, file_name)  # filename
        f.save(file_path)
        new_file = File(file_name=file_name, upload_date=datetime.utcnow())
        new_file.path = os.path.abspath(file_path)
        new_file.size = os.path.getsize(file_path)
        new_file.user_id = current_user.id
        new_file.description = form.description.data
        new_file.hash_sha = new_file.encrypt_string(new_file.file_name)
        db.session.add(new_file)
        db.session.commit()
        flash(f'{file_name} was successfully uploaded!!')
        return redirect(url_for('index'))
    return render_template('upload.html', form=form)
Example #15
0
def process():
	form = UploadForm()

	if form.validate_on_submit():
		file = request.files['upload_file']		
		filename = secure_filename(file.filename)

		if file and allowed_file(filename):
			df = create_pandas_df(file)

			if df is None:
				form.upload_file.errors.append("Your file is missing a column 'Address' or 'address'")
				return render_template('home.html', form=form)		
			else:

				upload_directory = get_upload_path()
				if not os.path.exists(upload_directory):
					os.makedirs(upload_directory)

				df.to_csv(os.path.join(upload_directory, filename), encoding='utf-8', index=False)
				return redirect(url_for('result', filename=filename))
		else:
			form.upload_file.errors.append("You must upload only .csv files")
			return render_template('home.html', form=form)	

	else:
		return render_template('home.html', form=form)	
Example #16
0
def upload_file():
    print(
        current_user.roles
    )  #returns either admin or end-user but next line always goes through?
    # if current_user.roles is 'admin':
    form = UploadForm()
    if request.method == 'POST':
        # check if the post request has the file part
        if 'file' not in request.files:
            flash('No file part')
            return redirect(request.url)
        file = request.files['file']
        name = request.form['text']
        user = current_user.id
        if file.filename == '':
            flash('No selected file')
            return redirect(request.url)
        if file and not allowed_file(file.filename):
            flash('Unsupported File Type')
            return redirect(request.url)
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            resstr, fileLOC = upload_file_to_s3(file, 'laneck')
            # print(type(fileLOC))
            fileLOC = ', '.join(fileLOC)
            # print(fileLOC)
            if store_fileInfo(fileLOC, name,
                              user):  #creates db entry for song e
                print('succesful upload')
                return redirect(url_for('music'))
            else:
                flash('Song already exists in the database')
                return redirect(request.url)
    return render_template('upload.html', form=form)
Example #17
0
def upload_file():
    form = UploadForm()
    if request.method == 'POST' and form.validate_on_submit():
        input_file = request.files['input_file']
        # Do stuff
    else:
        return render_template('index.html', form=form)
Example #18
0
def upload():
    form = UploadForm()
    posts = False
    path = ''
    if form.validate_on_submit():
        filename = secure_filename(form.file.data.filename)
        path = os.path.join(UPLOAD_PATH, form.file.data.filename)
        # form.file.data.save('uploads/' + filename)
        posts = True
        # return redirect(url_for('upload'))

    return render_template('upload.html', form=form, posts=posts, path=path)
    # return render_template('upload_comp.html', form=form)


# @app.route('/upload', methods=['GET', 'POST'])
# def upload():
#     form = UploadForm()

#     if form.validate_on_submit():
#         filename = secure_filename(form.file.data.filename)
#         form.file.data.save('uploads/' + filename)
#         return redirect(url_for('upload'))

#     return render_template('upload.html', form=form)
# def upload():
#     if form.validate_on_submit():
#         f = form.photo.data
#         filename = secure_filename(f.filename)
#         f.save(os.path.join(
#             app.instance_path, 'photos', filename
#         ))
#         return redirect(url_for('index'))

#     return render_template('upload.html', form=form)
Example #19
0
def videos():
    if not session.get('logged_in'):
        abort(401)

        # Instantiate  form class
    video_upload = UploadForm()

    # Validate file upload on submit
    if request.method == 'POST':
        if video_upload.validate_on_submit():
            print(request.files['video_test'])
            app.logger.info('posted')
            # Get file data and save to your uploads folder
            videos = video_upload.video_test.data

        filename = secure_filename(videos.filename)
        videos.save(os.path.join(app.config['SAVED_FOLDER'], filename))

        flash('Video Saved', 'success')
        return redirect(url_for('videos'))

    video_file_list = get_uploaded_videos()
    print(video_file_list)

    flash_errors(video_upload)
    return render_template('videos.html',
                           form=video_upload,
                           uploaded_videos=video_file_list)
Example #20
0
def upload_image():
    if not 'signed_user' in session:
        return json.dumps({
            'answer': False,
            'details': 'You are not signed in'
        })
    form = UploadForm()

    if not form.validate():
        return json.dumps({'answer': False, 'details': 'File is invalid'})

    file = form.file.data

    coordinates = json.loads(request.form.get('coordinates'))

    filename = secure_filename(session['signed_user'] +
                               str(datetime.datetime.now()) + file.filename)
    filepath = os.path.join(os.path.abspath('images'), filename)

    file.save(filepath)
    img = Image.open(filepath)
    coordinates_to_crop = (coordinates['left'], coordinates['top'],
                           coordinates['left'] + coordinates['width'],
                           coordinates['top'] + coordinates['height'])
    cropped = img.crop(coordinates_to_crop)
    cropped.save(filepath)
    res = User().upload_image(filename, session['signed_user'])
    User().set_online(session['signed_user'])
    if not res:
        return json.dumps({
            'answer': False,
            'details': "You can upload not more than 5 images"
        })
    return json.dumps({'answer': True})
Example #21
0
def change_icon():
    form = UploadForm()
    img_url = ''
    if form.validate_on_submit():
        #获得后缀
        suffix = os.path.splitext(form.icon.data.filename)[1]

        #拼接文件名
        filename = random_string() + suffix
        #保存
        photos.save(form.icon.data, name=filename)

        # 生成缩略图
        pathname = os.path.join(current_app.config['UPLOADED_PHOTOS_DEST'],
                                filename)
        #打开文件
        img = Image.open(pathname)
        img.thumbnail((128, 128))
        img.save(pathname)

        #如果用户头像不是默认,说明上传了头像
        #如果更新了,则删除原来的
        if current_user.icon != 'default.jpg':
            os.remove(
                os.path.join(current_app.config['UPLOADED_PHOTOS_DEST'],
                             current_user.icon))
        current_user.icon = filename
        db.session.add(current_user)
        flash("头像已经保存")
        return redirect(url_for('users.change_icon'))

    img_url = photos.url(current_user.icon)
    return render_template('user/change_icon.html', form=form, img_url=img_url)
Example #22
0
def upload_file():
    form = UploadForm()
    if request.method == 'POST':
        # check if the post request has the file part
        if 'file' not in request.files:
            flash('No file part')
            return redirect(request.url)
        file = request.files['file']
        # if user does not select file, browser also
        # submit an empty part without filename
        if file.filename == '':
            flash('No selected file')
            return redirect(request.url)
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            print(filename)

            newFile = Post(title=form.title.data,
                           data=file.read(),
                           description=form.description.data,
                           user_id=current_user.id,
                           filename=filename)
            db.session.add(newFile)
            db.session.commit()

        if form.validate_on_submit():
            flash('Your post has been created!', 'success')
            return redirect(url_for('upload_file', filename=filename))

    return render_template('upload.html',
                           title='Upload',
                           form=form,
                           legend='Upload')
Example #23
0
def upload():
    form = UploadForm()
    if form.validate_on_submit():
        f = form.upload.data
        filename = secure_filename(f.filename)
        f.save(os.path.join(app.instance_path, filename))
        if filename.endswith(".mp3"):
            sound = AudioSegment.from_mp3(
                os.path.join(app.instance_path, filename))
            filenamemp3 = filename.split('.')[0] + '.wav'
            sound.export(os.path.join(app.instance_path, filenamemp3),
                         format='wav')
            os.remove(os.path.join(app.instance_path, filename))
            filename = filenamemp3
        s = Song(filename=filename, user_id=int(current_user.id))
        db.session.add(s)

        df = getbeats(os.path.join(app.instance_path, filename))
        for row in df.itertuples():
            b = Beat(start=row[6],
                     end=row[7],
                     flatness=row[1],
                     rms=row[2],
                     specbw=row[3],
                     mfcc=row[4],
                     note=row[5],
                     n_group=row[9],
                     idx=row[8],
                     song_id=Song.query.filter_by(
                         user_id=int(current_user.id)).all()[-1].id)
            db.session.add(b)

        db.session.commit()
        return redirect(url_for('profile'))
    return render_template('upload.html', title='Upload New Track', form=form)
Example #24
0
def import_data(audit_id):
    if audit_id == -1:
        redirect(url_for('audit_report'))
    form = UploadForm()
    if request.method == 'POST' and form.validate_on_submit():
        audit_id = form.audit_id.data
        this_audit = Audit.query.filter_by(id=audit_id).first()
        # check if the post request has the file part
        if 'file' not in request.files:
            flash('No file part')
            return redirect(request.url)
        file = request.files['file']
        # if user does not select file, browser also
        # submit an empty part without filename
        if file.filename == '':
            flash('No selected file')
            return redirect(request.url)
        if file and allowed_file(file.filename):
            filename_orginal = file.filename
            filename = secure_filename(
                str(audit_id) + '-' +
                time.strftime('%Y%m%d%H%M%S', time.gmtime(time.time())))
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        return redirect(
            url_for('accept_data', audit_id=this_audit.id, filename=filename))
    form.audit_id.default = audit_id
    form.process()
    return render_template('audit/upload_data.html', form=form)
Example #25
0
def edit(request, upload_id):
    if request.method == "GET":
        upload = get_object_or_404(Upload, id=upload_id)
        upload_form = UploadForm(instance=upload)
        context = {'upload': upload, 'form': upload_form}
        return render(request, "app/edit_upload.html", context)
    else:
        upload_form = UploadForm(request.POST)
        if upload_form.is_valid():
            upload_form.save()
            messages.success(request,
                             "O registro foi atualizado com sucesso!!")
            return redirect('show', upload_id=upload_id)
        else:
            messages.error(request, "Algo deu errado!!")
            return redirect('show', upload_id=upload_id)
Example #26
0
def upload(problem_num):
    user = g.user
    form = UploadForm()
    if form.validate_on_submit():
        file_data = form.upload.data

        # renames file to username_prob_num.file_ext
        file_ext = file_data.filename.split('.')[1]
        file_name = secure_filename(user.username + "_" + problem_num + '.' +
                                    file_ext)

        if file_data and allowed_file(file_name):

            file_path_user_folder = os.path.join(app.config['UPLOAD_FOLDER'],
                                                 "Teams", user.username,
                                                 file_name)

            file_path_cs_java = os.path.join(UPLOAD_FOLDER,
                                             "cs_java_files_to_grade")

            # if file exists, report it's still waiting to be graded
            if not os.path.isfile(file_path_user_folder):
                # saves file to folder, will delete if test failed
                file_data.save(file_path_user_folder)

                # changes file status
                user.files[int(problem_num) - 1].status = "Submitted"
                db.session.commit()
                """ THIS SECTION NEEDS WORK:
                    MAKE IT AUTO GRADE!

                file_ext = file_name.split('.')[1]
                # if file is cpp or python, auto grade
                if file_ext == 'py':
                    if grade_submission(user, file_path_user_folder, file_name, problem_num):
                        update_file_status(user, problem_num, "Solved")
                        update_score(user, int(problem_num))
                    else:
                        update_file_status(user, problem_num, "Failed")
                        os.remove(file_path_user_folder)
                # if java or cs file or cpp, save to cs_java folder to await manual grading
                else:

                """
                # right now it just dumps the file into a folder to be manually graded
                copyanything(file_path_user_folder, file_path_cs_java)

                flash("File " + file_name + " uploaded successfully!")
                return redirect(url_for('index'))
            else:
                flash(
                    "Your submission is waiting to be graded. Please wait until you receive feedback to submit again."
                )
        else:
            flash(
                "Please choose a file with extension '.cs', '.java', '.cpp', or '.py'"
            )
    return render_template(problem_num + '.html',
                           title="Problem " + problem_num,
                           form=form)
Example #27
0
def upload():
    from app.forms import UploadForm

    form = UploadForm()
    if form.validate_on_submit():
        action_msg = uploadFile(form.ros_file.data, form.manifest_file.data,
                                form.comments.data)
        action_list = action_msg.split(";")
        if len(action_list) != 2:
            action_error_msg = action_list[0]
        else:
            action_error_msg = action_list[0]
            proxy_name = action_list[1]
        url_base = url()
        succeed = (action_error_msg == "None")
        if succeed == True:
            return render_template('download.html',
                                   download_url="download/" + proxy_name)
        else:
            return render_template('upload.html',
                                   form=form,
                                   action_error_msg=action_error_msg,
                                   succeed=succeed)

    return render_template('upload.html',
                           form=form,
                           action_error_msg=None,
                           succeed=False)
Example #28
0
def icon():
    form = UploadForm()
    if form.validate_on_submit():
        # 提取上传文件信息
        photo = form.photo.data
        # 提取文件后缀
        suffix = os.path.splitext(photo.filename)[1]
        # 生成随机文件名
        filename = random_string() + suffix
        # 保存上传文件
        photos.save(photo, name=filename)
        # 拼接文件路径名
        pathname = os.path.join(current_app.config['UPLOADED_PHOTOS_DEST'],
                                filename)
        # 打开文件
        img = Image.open(pathname)
        # 设置尺寸
        img.thumbnail((64, 64))
        # 重新保存
        img.save(pathname)
        # 删除原来的头像文件(默认头像除外)
        if current_user.icon != 'default.jpg':
            os.remove(
                os.path.join(current_app.config['UPLOADED_PHOTOS_DEST'],
                             current_user.icon))
        # 保存头像
        current_user.icon = filename
        db.session.add(current_user)
        flash('头像修改成功')
    img_url = url_for('static', filename='upload/' + current_user.icon)
    return render_template('user/icon.html', form=form, img_url=img_url)
Example #29
0
def change_icon():
    form = UploadForm()
    if form.validate_on_submit():
        # 获取后缀
        suffix = os.path.splitext(form.icon.data.filename)[1]
        # 随机文件名
        filename = random_string() + suffix
        photos.save(form.icon.data, name=filename)
        # 生成缩略图
        pathname = os.path.join(current_app.config['UPLOADED_PHOTOS_DEST'],
                                filename)
        img = Image.open(pathname)
        img.thumbnail((128, 128))
        img.save(pathname)
        # 删除原来的头像(不是默认头像时才需要删除)
        if current_user.icon != 'default.jpeg':
            os.remove(
                os.path.join(current_app.config['UPLOADED_PHOTOS_DEST'],
                             current_user.icon))
        # 保存到数据库
        current_user.icon = filename
        db.session.add(current_user)
        return redirect(url_for('user.change_icon'))
    img_url = photos.url(current_user.icon)
    return render_template('user/change_icon.html', form=form, img_url=img_url)
Example #30
0
def upload():

    # Instantiate your form class
    form = UploadForm()

    # Validate file upload on submit
    if request.method == 'POST':
        if form.validate_on_submit():

            desc = request.form['description']
            photo = request.files['photo']

            filename = secure_filename(photo.filename)
            photo.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))

            jsMessage = jsonify(message="File Upload Successful",
                                filename=filename,
                                description=desc)
            return jsMessage

        else:
            error = form_errors(form)
            for e in error:
                flash(e, 'danger')

            jsError = jsonify(errors=error)
            return jsError