3 回答
TA貢獻2003條經驗 獲得超2個贊
接受的答案不再有效?,F在您需要使用上下文來找到正確的文件夾。類似下面的代碼應該可以工作。
import logging
import azure.functions as func import mimetypes
def main(req: func.HttpRequest, context: func.Context) -> func.HttpResponse:
logging.info('processed request for home funciton')
filename = f"{context.function_directory}/static/index.html"
with open(filename, 'rb') as f:
mimetype = mimetypes.guess_type(filename)
return func.HttpResponse(f.read(), mimetype=mimetype[0])
TA貢獻2019條經驗 獲得超9個贊
假設您正在按照官方快速入門教程Create an HTTP triggered function in Azure學習 Azure Function for Python,那么您創建了一個函數static-file來處理這些靜態文件,這些文件位于static-file您想要的路徑或其他路徑中MyFunctionProj,index.html依此logo.jpg類推。
這是我的示例代碼,如下所示。
import logging
import azure.functions as func
import mimetypes
def main(req: func.HttpRequest) -> func.HttpResponse:
logging.info('Python HTTP trigger function processed a request.')
name = req.params.get('name')
if not name:
try:
req_body = req.get_json()
except ValueError:
pass
else:
name = req_body.get('name')
if name:
#return func.HttpResponse(f"Hello {name}!")
path = 'static-file' # or other paths under `MyFunctionProj`
filename = f"{path}/{name}"
with open(filename, 'rb') as f:
mimetype = mimetypes.guess_type(filename)
return func.HttpResponse(f.read(), mimetype=mimetype[0])
else:
return func.HttpResponse(
"Please pass a name on the query string or in the request body",
status_code=400
)
瀏覽器中的結果如下圖。

我的api的文件結構static-file如下。

該index.html文件的內容如下。
<html>
<head></head>
<body>
<h3>Hello, world!</h3>
<img src="http://localhost:7071/api/static-file?name=logo.jpg"></img>
</body>
</html>
注意:對于在本地運行,該index.html文件可以正常顯示logo.jpg。如果部署到 Azure,則需要在tagcode的屬性末尾添加查詢參數,例如.srcimg<img src="http://<your function name>.azurewebsites.net/api/static-file?name=logo.jpg&code=<your code for /api/static-file>"></img>
希望能幫助到你。
TA貢獻1824條經驗 獲得超8個贊
我做的很簡單,不介意內容(上傳文件),它不是那樣工作的:)
if command:
return func.HttpResponse(status_code=200,headers={'content-type':'text/html'},
body=
"""<!DOCTYPE html>
<html>
<body>
<form enctype = "multipart/form-data" action = "returnNameTrigger?save_file.py" method = "post">
<p>File: <input type = "file" name = "filename" /></p>
<p><input type = "submit" value = "Upload" /></p>
</form>
</body>
</html>
""")
添加回答
舉報
