- 前端上传:
将文件拖到此处,或点击上传
其中重要的选项为 action,:file-list, auto-upload, 以及一些钩子函数
action为要上传的地址,若想不自动上传auto-upload设为false,且点击上传相关按钮才上传到后台的话 action设为空即可。
file-list为上传的文件暂存的列表,可通过设置multiple设置允许多文件上传,设置limit限制上传文件个数。
钩子函数可根据具体需求定制,一般常用的钩子函数包括on-change,即文件列表改变时的操作。
提交
提交按钮,并出发doFunction函数发送图片给后端。
jsp基本对象如下:
export default {
data() {
return {
headers: {
'Content-Type': 'multipart/form-data'
},
fileList: [],
resultsrc: '',
resvisible: false
//...
}
},
//method:{}
}
fileList是文件列表
resultsrc是后端返回的图片url 用于前端显示
resvisible是是否显示返回结果默认false
提交到后端的脚本简单实现如下
doFunction() {
var that = this
const formData = new FormData()
//假设题提交一个文件,则如下,这里的filename要与后端接口要求的一致 .raw获得源文件
formData.append(‘filename’, that.fileList[0].raw)
// 请求后端API服务,请求方法为post,请求体字段为json格式 text
//{ responseType: 'blob' }设置相应体类型blob非常重要
axios.post('http://127.0.0.1:5000/v1/changedetection',
formData,
{ responseType: 'blob' }
).then((response) => {
if (response.status === 'ok') {
console.log('上传成功')
}
这里也是关键,调用window的这个方法URL方法 该方法参数可以是blob类型
const src = window.URL.createObjectURL(response.data)
that.resultsrc = src
that.resvisible = true
that.$message({
showClose: true,
message: '请求完成!',
type: 'success'
})
}).catch((error) => {
console.log(error)
that.result = ''
that.visible = false
that.$message({
showClose: true,
message: '请求出现异常!',
type: 'error'
})
})
}
}
显示后端返回的图片
后端处理结果:
- 下面看一下后端有几个坑。。。
- 跨域问题: from flask_cors import CORS 即可解决
-
@app.route('********', methods=['GET', 'POST']) def function(): if request.method == 'POST': import base64 file = request.files['filename'] file = file.read() #读为字节流 file = cv2.imdecode(np.frombuffer(file, np.uint8), cv2.IMREAD_COLOR) #解码为ndarray “ 操作生成out 也是ndarray格式 这里不能直接使用out.tobytes()转字节流,会有格式问题 应该先编码为图片格式在转字节流 ,若后端直接读取图片并返回可直接 open(path, 'rb').read()得到字节流 ” # img_stream = out.tobytes() success,encoded_image = cv2.imencode(".png", out) img_stream = encoded_image.tostring() response = make_response(img_stream) response.headers['Content-Type'] = 'image/png' #返回的内容类型必须修改 return response



