用Flask写个简单的传输图片导出图片的网页
时间: 2024-10-01 17:13:05 浏览: 27
在Flask中创建一个简单的上传图片并下载的网页,首先你需要安装Flask和相关的文件上传库,比如Flask-Uploads。以下是基本步骤:
1. **环境准备**:
确保已经安装了Python和Flask。如果还没有安装,可以通过pip来安装:
```
pip install flask flask-uploads
```
2. **创建Flask应用**:
在一个名为app.py的文件中,初始化Flask应用:
```python
from flask import Flask, request, send_file
from flask_uploads import UploadSet, configure_uploads, IMAGES
app = Flask(__name__)
app.config['UPLOADED_IMAGES_DEST'] = 'uploads/' # 图片存储路径
images = UploadSet('images', IMAGES)
configure_uploads(app, images)
```
3. **路由配置**:
定义两个路由,一个是接收文件上传,另一个是提供已上传图片的下载:
```python
@app.route('/upload-image', methods=['POST'])
def upload_image():
if 'image' not in request.files:
return "No image data found"
file = images.save(request.files['image'])
return f"Image uploaded successfully. File path: {file}"
@app.route('/download/<filename>')
def download_image(filename):
try:
return send_file(f'{app.config["UPLOADED_IMAGES_DEST"]}{filename}', as_attachment=True)
except FileNotFoundError:
return "File not found", 404
```
4. **运行应用**:
添加下面的代码启动服务:
```python
if __name__ == '__main__':
app.run(debug=True) # 开发模式下调试
```
现在访问`http://localhost:5000/upload-image`进行上传图片,成功后用浏览器地址栏访问`http://localhost:5000/download/<filename>`下载图片,其中`<filename>`是你上传文件的实际名称。
阅读全文