python网页开发实现本地上传_python实现本地图片上传到服务区
时间: 2023-08-05 16:51:54 浏览: 98
可以使用Python的Web框架,如Flask或Django,通过HTML表单实现本地图片上传到服务器的功能。
以下是一个使用Flask框架实现本地图片上传的示例代码:
```python
from flask import Flask, request, redirect, url_for
import os
app = Flask(__name__)
UPLOAD_FOLDER = './uploads' # 存储上传文件的目录
@app.route('/')
def index():
return '''
<html>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="Upload">
</form>
</body>
</html>
'''
@app.route('/upload', methods=['POST'])
def upload():
file = request.files['file']
if file:
filename = file.filename
file.save(os.path.join(UPLOAD_FOLDER, filename))
return redirect(url_for('uploaded_file', filename=filename))
else:
return "Upload Failed"
@app.route('/uploads/<filename>')
def uploaded_file(filename):
return '''
<html>
<body>
<h3>Uploaded Image:</h3>
<img src="''' + url_for('static', filename='uploads/' + filename) + '''">
</body>
</html>
'''
if __name__ == '__main__':
app.run(debug=True)
```
在上面的示例中,`UPLOAD_FOLDER` 变量指定了存储上传文件的目录。`index()` 函数渲染一个包含文件上传表单的HTML页面。`upload()` 函数处理表单提交,并将文件保存到指定的目录中。`uploaded_file()` 函数展示上传的图片。
当你运行上面的代码后,可以在浏览器中访问 `http://localhost:5000/` 来上传图片。上传成功后,你可以在 `http://localhost:5000/uploads/<filename>` 查看上传的图片。
阅读全文
相关推荐
![apk](https://img-home.csdnimg.cn/images/20250102104920.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)