qr-scanner/handlers/export.go

58 lines
1.2 KiB
Go

package handlers
import (
"net/http"
"os"
"path/filepath"
"github.com/gin-gonic/gin"
"qr-scanner/services"
)
type ExportHandler struct {
store *services.TaskStore
exporter *services.Exporter
}
func NewExportHandler(store *services.TaskStore, exporter *services.Exporter) *ExportHandler {
return &ExportHandler{store: store, exporter: exporter}
}
func (h *ExportHandler) Download(c *gin.Context) {
taskID := c.Param("taskID")
task, ok := h.store.Get(taskID)
if !ok {
fail(c, http.StatusNotFound, "任务不存在")
return
}
if task.Status == services.TaskExpired {
fail(c, http.StatusGone, "任务已过期")
return
}
if task.ExcelPath != "" {
if _, err := os.Stat(task.ExcelPath); err == nil {
c.FileAttachment(task.ExcelPath, filepath.Base(task.ExcelPath))
return
}
}
results := task.Results()
if len(results) == 0 {
fail(c, http.StatusConflict, "结果尚未生成")
return
}
out := task.ExportFilename()
if err := h.exporter.Export(results, out); err != nil {
fail(c, http.StatusInternalServerError, "生成Excel失败")
return
}
task.ExcelPath = out
h.store.Put(task)
c.FileAttachment(out, filepath.Base(out))
}