Files
bj_power/bj_power_mes/internal/handler/attachment.go
T

85 lines
2.4 KiB
Go
Raw Normal View History

package handler
import (
"net/http"
"os"
"path/filepath"
"bj_power_mes/common/httpx"
"bj_power_mes/internal/logic"
"bj_power_mes/internal/svc"
)
// AttachmentUploadHandler POST /attachment/upload 上传并登记(multipart: bizType,bizId,file
func AttachmentUploadHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if err := r.ParseMultipartForm(32 << 20); err != nil {
httpx.BadRequest(w, "表单解析失败")
return
}
bizType := r.FormValue("bizType")
bizId := r.FormValue("bizId")
if bizType == "" || bizId == "" {
httpx.BadRequest(w, "bizType 与 bizId 必填")
return
}
rel, fname, size, err := saveUploadFileFull(r, "file", svcCtx.Config.Upload.Dir)
if err != nil {
httpx.Fail(w, 3311, "文件保存失败:"+err.Error())
return
}
rec, err := logic.New(svcCtx).AddAttachment(r.Context(), bizType, bizId, fname, rel, int(size), operator(r, ""))
if err != nil {
httpx.Fail(w, 3311, err.Error())
return
}
httpx.Ok(w, rec)
}
}
// AttachmentListHandler GET /attachments?bizType=&bizId= 附件列表
func AttachmentListHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
data, err := logic.New(svcCtx).ListAttachments(r.Context(), q.Get("bizType"), q.Get("bizId"))
if err != nil {
httpx.Fail(w, 3312, err.Error())
return
}
httpx.Ok(w, data)
}
}
// AttachmentDownloadHandler GET /attachment/download?name= 下载
func AttachmentDownloadHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
name := r.URL.Query().Get("name")
if name == "" {
httpx.BadRequest(w, "缺少 name")
return
}
serveUploadFile(w, r, svcCtx.Config.Upload.Dir, name)
}
}
// AttachmentDeleteHandler POST /attachment/delete {id} 删除(记录+物理文件)
func AttachmentDeleteHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req struct {
Id int `json:"id"`
}
if err := httpx.ParseJSON(r, &req); err != nil {
httpx.BadRequest(w, "请求体解析失败")
return
}
att, err := logic.New(svcCtx).DeleteAttachment(r.Context(), req.Id)
if err != nil {
httpx.Fail(w, 3313, err.Error())
return
}
full := filepath.Join(svcCtx.Config.Upload.Dir, filepath.FromSlash(att.FilePath))
_ = os.Remove(full)
httpx.OkMessage(w, "删除成功", nil)
}
}