python - 如何在 html 页面中上传文件,在使用 python 的 azure 函数中使用 http 触发器?
问题描述
我想有一些方法,如何上传文件(可以是没有 php 的 html,或者一些交互式 azure 上传页面,等等),并通过我的 URL 参数我想发送参数,这将运行其余的代码使用这个上传的文件(我至少需要将它保存到 blob)。
我需要一个rest api,所以我选择了azure functions。
有什么办法可以在python中做到这一点?我在 C# 中看到了很多示例,但是 python 的文档是有限的。
多谢!
解决方案
关于这个问题,您可以使用Html Form
它来实现它。
例如
- 网页
<!DOCTYPE html>
<html>
<script type="text/javascript"
src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.4.1.js">
</script>
<body>
<form enctype="multipart/form-data">
<input name="file" type="file" />
<input type="button" value="Upload" />
</form>
<progress></progress>
<script language="javascript" type="text/javascript">
$(document).ready(function(){
$(':file').on('change', function () {
var file = this.files[0];
console.log(file)
$(':button').on('click', function () {
var form = new FormData()
form.append('file',file)
$.ajax({
// Your server script to process the upload
url: '<your azure function app url>',
type: 'POST',
crossDomain: true,
enctype: 'multipart/form-data',
// Form data
data:form,
// Tell jQuery not to process data or worry about content-type
// You *must* include these options!
cache: false,
contentType: false,
processData: false,
success : function(data){console.log(data);},
// Custom XMLHttpRequest
xhr: function () {
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) {
// For handling the progress of the upload
myXhr.upload.addEventListener('progress', function (e) {
if (e.lengthComputable) {
$('progress').attr({
value: e.loaded,
max: e.total,
});
}
}, false);
}
return myXhr;
}
});
});
});
});
</script>
</body>
</html>
- 函数代码(将文件上传到 Azure blob)
import logging
import os
import azure.functions as func
from azure.storage.blob import BlobServiceClient, BlobClient
def main(req: func.HttpRequest) -> func.HttpResponse:
logging.info('Python HTTP trigger function processed a request.')
try:
file= req.files.get('file')
logging.info(file.filename)
connect_str="your storage account connection string"
container="your container name"
blob_service_client = BlobServiceClient.from_connection_string(connect_str)
blob_client =blob_service_client.get_blob_client(container=container,blob=file.filename)
blob_client.upload_blob(file)
except Exception as ex:
logging.info(ex.args)
return func.HttpResponse(f"the file {file.filename} upload successfully")
推荐阅读
- wix - 您如何在 Wix 引导程序卸载上卸载另一个应用程序?
- qr-code - 二维码 - 自动重定向到 URL
- node.js - 如何将 .dbf 文件中的数据导入 mongodb 集合?
- algorithm - 大 O 表示法 - 对循环的怀疑
- mongodb - 如何在mongodb中选择几个字符?
- php - WordPress 电子邮件共享按钮未在 Outlook 中打开
- android - 当应用程序在前台运行时,我没有收到推送通知
- redirect - 在不丢失反向链接的情况下进行 301 NGINX 重定向的正确方法
- tomcat - 在 Tomcat Websocket / Serverendpoint 中使用 CDI/注入
- python - Matplotlib 无法绘制只有 NaN 值的 DateTime 系列