首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Sanic中执行文件上传

如何在Sanic中执行文件上传
EN

Stack Overflow用户
提问于 2018-02-22 14:44:16
回答 3查看 6.9K关注 0票数 11

我试图在Sanic上执行文件上传,但是它不能正常工作,烧瓶的正常语法似乎与sanic不太一样。

我甚至不能访问文件名或保存方法来将上传的文件保存到给定的目录。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2018-02-22 14:51:43

经过长时间的挣扎,我发现下面的代码正在工作

代码语言:javascript
复制
@app.route("/upload", methods=['POST'])
async def omo(request):
    from sanic import response
    import os
    import aiofiles
    if not os.path.exists(appConfig["upload"]):
        os.makedirs(appConfig["upload"])
    async with aiofiles.open(appConfig["upload"]+"/"+request.files["file"][0].name, 'wb') as f:
        await f.write(request.files["file"][0].body)
    f.close()

    return response.json(True)
票数 13
EN

Stack Overflow用户

发布于 2019-06-18 20:46:31

上面的答案很好。几个小的改进:

(1)既然我们使用Sanic,那么让我们尝试异步地执行io文件:

代码语言:javascript
复制
async def write_file(path, body):
    async with aiofiles.open(path, 'wb') as f:
        await f.write(body)
    f.close()

(2)确保文件不太大,以便使服务器崩溃:

代码语言:javascript
复制
def valid_file_size(file_body):
    if len(file_body) < 10485760:
        return True
    return False

(3)检查文件名和文件类型,以确定正确的文件类型:

代码语言:javascript
复制
  def valid_file_type(file_name, file_type):
     file_name_type = file_name.split('.')[-1]
     if file_name_type == "pdf" and file_type == "application/pdf":
         return True
     return False

(4)确保文件名不具有危险/不安全字符。您可以在werkzeug.utils:http://flask.pocoo.org/docs/0.12/patterns/fileuploads/中使用http://flask.pocoo.org/docs/0.12/patterns/fileuploads/函数

(5)这一守则将所有内容汇集在一起:

代码语言:javascript
复制
async def process_upload(request):
        # Create upload folder if doesn't exist
        if not os.path.exists(app.config.UPLOAD_DIR):
            os.makedirs(app.config.UPLOAD_DIR)

        # Ensure a file was sent
        upload_file = request.files.get('file_names')
        if not upload_file:
            return redirect("/?error=no_file")

        # Clean up the filename in case it creates security risks
        filename = secure_filename(upload_file.name)

        # Ensure the file is a valid type and size, and if so
        # write the file to disk and redirect back to main
        if not valid_file_type(upload_file.name, upload_file.type):
            return redirect('/?error=invalid_file_type')
        elif not valid_file_size(upload_file.body):
            return redirect('/?error=invalid_file_size')
        else:
            file_path = f"{app.config.UPLOAD_DIR}/{str(datetime.now())}.pdf"
            await write_file(file_path, upload_file.body)
            return redirect('/?error=none')

我在Sanic中创建了一篇关于如何处理文件上传的博文。我添加了一些文件验证和异步文件写入。我希望其他人发现这一点很有帮助:

https://blog.fcast.co/2019/06/16/file-upload-handling-using-asynchronous-file-writing/

票数 9
EN

Stack Overflow用户

发布于 2019-04-24 10:35:35

下面是一个特定文件类型的文件上传示例(此示例用于pdf文件)

代码语言:javascript
复制
from sanic import Sanic
from sanic.response import json
from pathlib import os
from datetime import datetime


app = Sanic()

config = {}
config["upload"] = "./tests/uploads"



@app.route("/upload", methods=['POST'])
def post_json(request):
    if not os.path.exists(config["upload"]):
        os.makedirs(config["upload"])
    test_file = request.files.get('file')
    file_parameters = {
        'body': test_file.body,
        'name': test_file.name,
        'type': test_file.type,
    }
    if file_parameters['name'].split('.')[-1] == 'pdf':
        file_path = f"{config['upload']}/{str(datetime.now())}.pdf"
        with open(file_path, 'wb') as f:
            f.write(file_parameters['body'])
        f.close()
        print('file wrote to disk')

        return json({ "received": True, "file_names": request.files.keys(), "success": True })
    else:
        return json({ "received": False, "file_names": request.files.keys(), "success": False, "status": "invalid file uploaded" })

有关其他请求类型的示例,请参阅正式文档(data.html)

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48930245

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档