获取上传到Flask的文件的路径 [英] Get path of file uploaded to Flask

查看:112
本文介绍了获取上传到Flask的文件的路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Python Web应用程序,该Web应用程序在Web浏览器中本地运行,以提供方便的界面,处理用户选择的文件并保存处理后的数据.我需要添加在选定文件的同一文件夹中创建新子目录的功能(即,如果文件是path/fname.txt,则需要创建path/fname/,可以在其中放置处理后的数据).如何访问该文件路径?

I have a Python web application that runs locally in a web browser for interface convenience, processes files that a user selects, and saves processed data. I need to add the feature that creates a new subdirectory in the same folder where the file was selected (i.e., if the file is path/fname.txt, I need to create path/fname/ where I can put processed data). How do I access this path to the file?

在其他项目中,我分别询问了路径,但这很笨拙,我不想让用户对每个文件执行此无关紧要的步骤.

In other projects I have asked for the path separately, but that's clunky and I'd rather not make the user do this extraneous step for each file.

@app.route('/getthefile', methods=['POST'])
def getthefile():
    file = request.files['myfile']
    filename = secure_filename(file.filename)
    new_path = os.path.abspath(filename)
    # gives me the wrong path

推荐答案

为了不公开有关客户端系统的不必要信息,仅将文件名与HTTP请求一起发送.完整路径未发送.看一看 HTTP multipart/form-data请求:

In order to not expose unnecessary information about the client's system, only the filename is sent with the HTTP request. The full path is not sent. Take a look at an HTTP multipart/form-data request:

Content-Type: multipart/form-data; boundary=AaB03x

--AaB03x
Content-Disposition: form-data; name="submit-name"

Larry
--AaB03x
Content-Disposition: form-data; name="files"; filename="file1.txt"
Content-Type: text/plain

... contents of file1.txt ...
--AaB03x--

如您所见,信息很少.没有提供路径.

As you can see, information is pretty minimal. The path is not provided.

类似地,文件API 仅允许访问文件名.

Similarly, the File API only allows access the filename.

很遗憾,您将无法从文件输入中获取完整路径.

So unfortunately, you won't be able to get the full path from a file input.

这篇关于获取上传到Flask的文件的路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆