This commit is contained in:
sunbeam 2024-12-30 17:04:19 +08:00
parent 9e2e759a7e
commit 354347b4e9
2 changed files with 96 additions and 3 deletions

71
main.py
View File

@ -1,10 +1,75 @@
from fastapi import FastAPI
from fastapi import FastAPI, File, UploadFile
from fastapi.staticfiles import StaticFiles
import os
from shutil import copyfileobj
import shutil
import subprocess
from fastapi.responses import FileResponse
app = FastAPI()
app.mount("/", StaticFiles(directory="./web", html=True))
app.mount("/tool", StaticFiles(directory="./web", html=True))
@app.get("/api/test/")
async def root():
return {"message": "Hello World"}
@app.post("/api/uploadfile/")
async def create_upload_file(file: UploadFile = File(...)):
try:
# 设置文件保存的路径
folder_path = './uploads/'
# 清空文件夹
shutil.rmtree(folder_path)
# 新建文件夹
os.makedirs(folder_path, exist_ok=True)
os.makedirs(folder_path+'gen/', exist_ok=True)
# 复制coderdbc程序
shutil.copy2("../dbc2c/coderdbc", folder_path)
file_location = os.path.join(folder_path, file.filename)
with open(file_location, "wb") as buffer:
copyfileobj(file.file, buffer)
# 执行二进制程序并等待其完成
command = [
folder_path+"coderdbc",
"-dbc", folder_path+file.filename,
"-out", folder_path+"gen/",
"-drvname", "CANmatrix",
"-nodeutils",
"-rw",
"-driverdir", # 这个参数后面没有值,所以它后面不应该有逗号
"-gendate"
]
result = subprocess.run(command, capture_output=True, text=True)
# 获取输出和错误
if result.stderr == "":
command = ['zip', '-r', folder_path+'gen/CANmatrix.zip', folder_path+'gen/CANmatrix']
# 使用subprocess.run执行命令
result = subprocess.run(command, capture_output=True, text=True)
return {"info": f"File {file.filename} uploaded successfully!",
"coderdbc_stdout":result.stdout,
"coderdbc_stderr":result.stderr,
}
except Exception as e:
return {"error": str(e)}
@app.get("/api/download/")
async def download_file():
try:
# 设置文件保存的路径
folder_path = './uploads/'
return FileResponse(path=folder_path+"gen/CANmatrix.zip", filename="CANmatrix.zip", media_type="application/zip")
except FileNotFoundError:
return JSONResponse(content={"message": "File not found"}, status_code=404)
def process_file(file_path, output_path):
with open(file_path, 'r') as file:
content = file.read()
with open(output_path, 'w') as file:
file.write(content.upper())
if __name__ == "__main__":
import uvicorn

View File

@ -8,5 +8,33 @@
<body>
<h1>Hello, FastAPI!</h1>
<p>This is an example of loading an HTML file using FastAPI.</p>
uploadfile
<form id="uploadForm" enctype="multipart/form-data">
<input type="file" name="file" id="file">
<input type="submit" value="Upload File">
</form>
<script>
// 使用jQuery处理表单提交
$('#uploadForm').submit(function(e) {
e.preventDefault(); // 阻止表单默认提交行为
var formData = new FormData(this); // 创建FormData对象
$.ajax({
url: '/api/uploadfile/', // 上传文件的API端点
type: 'POST',
data: formData,
contentType: false, // 不设置内容类型
processData: false, // 不处理数据
success: function(response) {
// 文件上传成功后,下载文件
window.location.href = '/api/download/'; // 重定向到下载API端点
},
error: function(xhr, status, error) {
alert('Upload error: ' + error);
}
});
});
</script>
</body>
</html>