我正在访问某个网站,我想上传一个文件。
我在python中编写了代码:
import requests
url = 'http://example.com'
files = {'file': open('1.jpg', 'rb')}
r = requests.post(url, files=files)
print(r.content)
但似乎没有上传文件,页面与初始页面相同。
我想知道如何上传文件。
该页面的源代码:
<html><head><meta charset="utf-8" /></head>
<body>
<br><br>
Upload<br><br>
<form action="upload.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="hidden" name="dir" value="/uploads/" />
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
答案 0 :(得分:3)
几点:
files
参数提交其他表单字段('dir','submit')import requests
url = 'http://example.com' + '/upload.php'
data = {'dir':'/uploads/', 'submit':'Submit'}
files = {'file':('1.jpg', open('1.jpg', 'rb'))}
r = requests.post(url, data=data, files=files)
print(r.content)
中包含文件的名称(这是可选的)代码:
namespace Detailing
{
public partial class MainForm : Form
{
public void hidePanels()
{
welcomePanel.Width = 0;
homePanel.Width = 0;
historyPanel.Width = 0;
savePanel.Width = 0;
}
public MainForm()
{
InitializeComponent();
Load += new EventHandler(MainForm_Load);
}
private void MainForm_Load(object sender, EventArgs e)
{
hidePanels();
welcomePanel.Width = 1306;
}
private void homeButton_Click(object sender, EventArgs e)
{
hidePanels();
homePanel.Width = 1306;
}
}
}
答案 1 :(得分:1)
首先,定义上传目录的路径,如
app.config['UPLOAD_FOLDER'] = 'uploads/'
然后定义允许上传的文件扩展名,
app.config['ALLOWED_EXTENSIONS'] = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])
现在假设您调用函数来处理上传文件,那么您必须编写类似这样的代码,
# Route that will process the file upload
@app.route('/upload', methods=['POST'])
def upload():
# Get the name of the uploaded file
file = request.files['file']
# Check if the file is one of the allowed types/extensions
if file and allowed_file(file.filename):
# Make the filename safe, remove unsupported chars
filename = secure_filename(file.filename)
# Move the file form the temporal folder to
# the upload folder we setup
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
# Redirect the user to the uploaded_file route, which
# will basicaly show on the browser the uploaded file
return redirect(url_for('YOUR REDIRECT FUNCTION NAME',filename=filename))
这样您就可以上传文件并将其存储在您找到的文件夹中。
我希望这会对你有所帮助。
感谢。