如何使用python在azure函数中使用http触发器在html页面中上传文件? [英] How to upload a file in html page, using http trigger in azure functions using python?
问题描述
我想有一种方法,如何上传文件(可以是不带php的html,也可以是一些交互式的天蓝色上传页面,无论如何),并希望通过我的URL参数发送参数,该参数将运行使用此上传文件的其余代码(ofc,我至少需要将其保存到blob).
I would like to have a some way, how to upload a file (could be html without php, or some interactive azure upload page, whatever), and through my URL params I would like to send parameters, which will run the rest of code using this uploaded file (ofc I need to save it to blob at least).
我需要一个REST API,所以我选择了Azure函数.
I need a rest api, so i chose azure functions.
有什么办法可以在python中做到吗?我在C#中看到了很多示例,但是python的文档非常有限.
Is there any way how to do it in python? I saw lots of examples in C#, but docs for python are limited.
非常感谢!
推荐答案
关于此问题,您可以使用 Html Form
来实现.
Regarding the issue, you can use Html Form
to implement it.
例如
- HTML页面
<!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")
-
为您配置CORS功能
Configure CORS for you function
测试
这篇关于如何使用python在azure函数中使用http触发器在html页面中上传文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!