我正在为企业聊天机器人进行 PoC,并使用 Azure OpenAI 部署到应用程序进行设置。所有 UI 内容均已修复,Cosmos DB 设置等。但我想添加的最后一件事是上传文件功能。但我无法真正弄清楚变量名称和/或值应该是什么,以便在前端允许这样做。有人有同样的问题可以帮助我吗?
尝试添加
ALLOW_FILE_UPLOADS = true,
ALLOWED_EXTENSIONS=.pdf,.docx,.txt,.jpg,.png,
FILE_UPLOADS=On,
MAX_CONTENT_LENGTH=50,
UPLOAD_DIR=wwwroot/uploads.
重新启动应用程序时,文件图标会快速出现,但很快就会消失,因此看起来像是正在工作
环境变量取决于框架或应用程序的内部处理。让我们确保为常见框架正确配置变量。
ALLOW_FILE_UPLOADS
,但确保代码能够读取它。import os
ALLOW_FILE_UPLOADS = os.getenv("ALLOW_FILE_UPLOADS", "false").lower() == "true"
ALLOWED_EXTENSIONS = os.getenv("ALLOWED_EXTENSIONS", "").split(",")
MAX_CONTENT_LENGTH = int(os.getenv("MAX_CONTENT_LENGTH", 50)) * 1024 * 1024 # MB to bytes
UPLOAD_DIR = os.getenv("UPLOAD_DIR", "./uploads")
print(f"File Uploads Allowed: {ALLOW_FILE_UPLOADS}")
print(f"Allowed Extensions: {ALLOWED_EXTENSIONS}")
print(f"Max Content Length: {MAX_CONTENT_LENGTH} bytes")
print(f"Upload Directory: {UPLOAD_DIR}")
对于 Azure 应用服务,
wwwroot/uploads
可能有效,但请使用 ./uploads
或 Blob 存储目录进行测试
wwwroot
文件夹中的 只读存储。
<form id="uploadForm" enctype="multipart/form-data">
<input type="file" id="fileInput" name="file" />
<button type="submit">Upload</button>
</form>
检查前端是否将文件发送到后端。
document.getElementById("uploadForm").addEventListener("submit", async (e) => {
e.preventDefault();
const fileInput = document.getElementById("fileInput");
const formData = new FormData();
formData.append("file", fileInput.files[0]);
const response = await fetch("https://your-app.azurewebsites.net/upload", {
method: "POST",
body: formData,
});
const result = await response.json();
console.log(result);
});
打开
应用服务日志:
日志:
2024-11-28 10:15:23.456 INFO app: Received upload request for file 'malicious.exe'
2024-11-28 10:15:23.457 ERROR app: File extension '.exe' is not allowed.
2024-11-28 10:15:23.458 ERROR app: Upload failed for file 'malicious.exe' - Unsupported file type.
2024-11-28 10:20:00.567 INFO app: Received upload request for file 'example.pdf'
2024-11-28 10:20:00.568 ERROR app: Directory 'D:\home\site\wwwroot\uploads' does not exist.
2024-11-28 10:20:00.569 ERROR app: Upload failed for file 'example.pdf' - Internal Server Error.
2024-11-28 10:25:00.123 INFO app: Received upload request for file 'Img.png'
2024-11-28 10:25:00.124 INFO app: File size: 21 KB
2024-11-28 10:25:00.125 INFO app: File extension '.png' is allowed.
2024-11-28 10:25:00.126 INFO app: Uploading 'Img.png' to Azure Blob Storage container 'uploads'
2024-11-28 10:25:01.345 INFO app: File 'Img.png' successfully uploaded to Azure Blob Storage.