flask传递多张图片流,并在前端展示图片的代码
时间: 2024-05-07 22:15:43 浏览: 19
后端代码:
```python
from flask import Flask, Response, jsonify, request
import base64
app = Flask(__name__)
@app.route('/api/images', methods=['POST'])
def get_images():
images = []
for file in request.files.getlist('images'):
image = file.read()
images.append(image)
return jsonify({'images': images})
if __name__ == '__main__':
app.run(debug=True)
```
前端代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>Multiple Image Upload</title>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
<input type="file" id="imageInput" multiple>
<button id="uploadBtn">Upload</button>
<div id="imagePreview"></div>
<script>
$('#uploadBtn').click(function() {
var formData = new FormData();
var files = $('#imageInput')[0].files;
for (var i = 0; i < files.length; i++) {
formData.append('images', files[i]);
}
$.ajax({
url: '/api/images',
type: 'POST',
data: formData,
processData: false,
contentType: false,
success: function(data) {
var images = data.images;
for (var i = 0; i < images.length; i++) {
var image = images[i];
var base64Image = btoa(String.fromCharCode.apply(null, new Uint8Array(image)));
$('#imagePreview').append('<img src="data:image/png;base64,' + base64Image + '">');
}
},
error: function(xhr, textStatus, errorThrown) {
console.log(xhr.responseText);
}
});
});
</script>
</body>
</html>
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)