def save_image(image, folder): filename = '{}.{}'.format(uuid.uuid4(), extension(image.filename)) image_set.save(image, folder=folder, name=filename) filename = compress_image(filename=filename, folder=folder) return filename
def process_user_avatar(file_storage, upload_set, size=300): """Center clipping, resize and then save the avatar.""" image = open_image(file_storage) image = center_crop(image) image = resize_square(image, size) ext = extension(file_storage.filename) return save_image(image, upload_set, ext)
def save_image(image, folder): """Function to generate the filename for the uploaded image""" filename = '{}.{}'.format(uuid.uuid4(), extension(image.filename)) image_set.save(image, folder=folder, name=filename) # We invoke the compress_image function and then it's stored within the # filename variable filename = compress_image(filename=filename, folder=folder) return filename
def upload(): for file in request.files.getlist('btn-upload'): if not uploads.extension_allowed(extension(file.filename)): flash( Markup( 'File extension "%s" is not allowed to be uploaded to this server' % extension(file.filename)), "warning") return redirect(url_for('main.index')) # save file file_name, file_extension = os.path.splitext(file.filename) folder = os.path.join(current_user.email, file_name) file_path = helper.resolve_folder_conflict( current_app.config['UPLOAD_FOLDER'], folder) saved_file_name = uploads.save(file, folder=file_path, name=file.filename) # get book meta meta = book_format.process(uploads.path(saved_file_name), file_path, file_name, file_extension[1:]) # move file if meta.title != meta.file_name: new_file_path = os.path.join(current_app.config['UPLOAD_FOLDER'], file_path, meta.title + file_extension) move(uploads.path(saved_file_name), new_file_path) if meta.cover_path: new_cover_path = os.path.join( current_app.config['UPLOAD_FOLDER'], file_path, meta.title + '.jpg') move(meta.cover_path, new_cover_path) # add book Books.add_book(meta) flash(Markup('File upload completed.'), "info") return redirect(url_for('main.index'))
def save(self, storage, folder=None, name=None): """ 文件上传补丁:替换已存在文件 This saves a `werkzeug.FileStorage` into this upload set. If the upload is not allowed, an `UploadNotAllowed` error will be raised. Otherwise, the file will be saved and its name (including the folder) will be returned. :param self: :return: :param storage: The uploaded file to save. :param folder: The subfolder within the upload set to save to. :param name: The name to save the file as. If it ends with a dot, the file's extension will be appended to the end. (If you are using `name`, you can include the folder in the `name` instead of explicitly using `folder`, i.e. ``uset.save(file, name="someguy/photo_123.")`` """ if not isinstance(storage, FileStorage): raise TypeError("storage must be a werkzeug.FileStorage") if folder is None and name is not None and "/" in name: folder, name = os.path.split(name) basename = self.get_basename(storage.filename) if name: if name.endswith('.'): basename = name + extension(basename) else: basename = name if not self.file_allowed(storage, basename): raise UploadNotAllowed() if folder: target_folder = os.path.join(self.config.destination, folder) else: target_folder = self.config.destination if not os.path.exists(target_folder): os.makedirs(target_folder) # if os.path.exists(os.path.join(target_folder, basename)): # basename = self.resolve_conflict(target_folder, basename) target = os.path.join(target_folder, basename) storage.save(target) if folder: return posixpath.join(folder, basename) else: return basename
def save_image(image): """ function to store images on the server """ temp_image = '{}.{}'.format(uuid.uuid4(), extension(image.filename)) image_set.save(image, folder='dogs', name=temp_image) image_path = image_set.path(filename=temp_image, folder='dogs') image = Image.open(image_path) if image.mode != "RGB": image = image.convert("RGB") if max(image.width, image.height) > 500: image.thumbnail((500, 500)) thumbnail_filename = '{}.jpg'.format(uuid.uuid4()) thumbnail_path = image_set.path(filename=thumbnail_filename, folder='dogs') image.save(thumbnail_path, optimize=True, quality=95) os.remove(image_path) return thumbnail_path, get_url(thumbnail_filename)
def save_storage(self, storage, category='default', filetype='image'): """保存文件 :param storage: 文件对象 :class:`~werkzeug.datastructures.FileStorage` object. :param category: 分类名称 :param filetype: 文件类型 """ files_dest = current_app.config['UPLOADED_FILES_DEST'] dirname = os.path.join(files_dest, category, self.today) # 创建目录 try: if not os.path.exists(dirname): os.makedirs(dirname) except OSError as e: log_error( u'[OSError] [FileUploadService.save_storage] exception:%s' % e) raise e # 保存文件到硬盘 filename_ext = extension(storage.filename).lower() uuid_hex = uuid.uuid4().hex filename = '%s.%s' % (uuid_hex, filename_ext) self.target_filename = os.path.join(dirname, filename) try: storage.save(self.target_filename) except Exception as e: raise e # 云oss存储的key self.key = '%s/%s/%s' % (category, self.today, filename) url = '' try: url = self._upload_oss() except Exception as e: log_debug(e) raise e return url
def detect(): if 'media' in request.files: file = request.files['media'] # print(file) name = file.filename ext = extension(name) if ext.lower() in IMAGES: filename = photos.save(file, name=f'photo.') path = os.path.join(app.config['UPLOADED_PHOTOS_DEST'], filename) # print(f'processing image at path {path}') elif ext.lower() in VIDEO: filename = videos.save(file, name=f'video.') path = os.path.join(app.config['UPLOADED_VIDEOS_DEST'], filename) # print(f'processing video at path {path}') else: return redirect('/') streamer.stop() streamer.set_media_source(path) return render_template("live.html", title="Detection Results") return redirect('/')
def test_extension(self): assert extension('foo.txt') == 'txt' assert extension('foo') == '' assert extension('archive.tar.gz') == 'gz' assert extension('audio.m4a') == 'm4a'
def upload(media, privacy='public', used_as='post'): try: paths = [] audio = tuple('wma m4a mp2 au'.split()) document = tuple( 'pdf txt ppt pptx xlsx zip htm html tar rar gz py pyd js exe cpp c' .split()) print(media) for file in media: print(file) print(file.mimetype) name = file.filename ext = extension(name) postname = name[:-(len(ext) + 1)] if ext.lower() in IMAGES: filetype = 'photo' filename = photos.save(file, name='Photo.') path = "/static/uploads/photos/{}".format(filename) paths.append(path) elif ext.lower() in AUDIO or ext.lower() in audio: filetype = 'audio' filename = audios.save(file, name='Audio.') path = "/static/uploads/audios/{}".format(filename) paths.append(path) elif ext.lower() in VIDEO: filetype = 'video' filename = videos.save(file, name='Video.') path = "/static/uploads/videos/{}".format(filename) paths.append(path) elif ext.lower() in DOCUMENTS or ext.lower() in document: filetype = 'document' filename = documents.save(file, name='Document.') path = "/static/uploads/documents/{}".format(filename) paths.append(path) else: pass print(paths) if len(paths) > 1: filetype = 'batch' else: filetype = filetype print(paths) print(filetype) new_upload = Gallery(upload_type=filetype, upload_used_as=used_as, upload_path=paths, privacy=privacy, timestamp=datetime.datetime.now()) db.session.add(new_upload) db.session.commit() return { 'result': 'done', 'path': paths, 'filetype': filetype, 'postname': postname } except Exception as e: print('error :' + str(e)) return {'result': 'failed'}