我正在尝试在我的系统上保存上传的文件。在特定的路径,但我在Windows中收到此错误。谁能告诉我我在哪里做错了?
系统:Windows 8.1 python版本:2.7
这是我的代码:
# -*- coding: utf-8 -*-
from werkzeug.serving import run_simple
from werkzeug.wrappers import BaseRequest, BaseResponse
import os
def view_file(req):
if not 'file' in req.files:
return BaseResponse('no file uploaded')
f = req.files['file']
s = "C:\Users\admin\Desktop\test"
f.save(s, f.filename)
return BaseResponse('File Saved!')
def upload_file(req):
return BaseResponse('''
<h1>Upload File</h1>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="Upload">
</form>
''', mimetype='text/html')
def application(environ, start_response):
req = BaseRequest(environ)
if req.method == 'POST':
resp = view_file(req)
else:
resp = upload_file(req)
return resp(environ, start_response)
if __name__ == '__main__':
run_simple('localhost', 5000, application, use_debugger=True)
这里是追溯:
Traceback (most recent call last):
File "C:\Users\admin\Desktop\test.py", line 30, in application
resp = view_file(req)
File "C:\Users\admin\Desktop\test.py", line 13, in view_file
f.save(s, f.filename)
File "C:\Python27\lib\site-packages\werkzeug\datastructures.py", line 2703, in
save
dst = open(dst, 'wb')
IOError: [Errno 22] invalid mode ('wb') or filename: 'C:\\Users\x07dmin\\Desktop
\test'
答案 0 :(得分:0)
看起来\a
被解释为a control character。
你应该写这样的路径:
s = "C:\\Users\\admin\\Desktop\\test"
如果您正在致电.save()
,则还必须关闭该文件:http://werkzeug.pocoo.org/docs/0.11/datastructures/#werkzeug.datastructures.FileStorage.save
此外,您需要提供.save()
的缓冲区大小。
所以试试:
f.save(s, buffer_size=16384)
f.close()
答案 1 :(得分:0)
我不知道你们为什么都把所有东西混在一起,只是保持它的整洁和干净。 创建两个名为“ app.py”和“ index.html”的文件,并在应用程序的根目录中创建一个名为“ upload”的文件夹
index.html
<h1>Upload File</h1>
<form action="/uploader" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="Upload">
</form>
app.py
from flask import Flask, request,render_template
from werkzeug import secure_filename
import os
app = Flask(__name__)
uploads_dir = "upload"
@app.route("/")
def index():
return render_template('index.html')
@app.route('/uploader', methods = ['GET', 'POST'])
def uploader():
if request.method == 'POST':
input = request.files['file']
input.save(os.path.join(uploads_dir, secure_filename(input.filename)))
#print(input)
return "<h2>Successfully uploaded</h2>"
if __name__ == '__main__':
app.run()
保存文件后,您还可以重定向到其他页面:
return render_template(otherpage.html)