| | |
| | | "bytes" |
| | | "fmt" |
| | | "github.com/gin-gonic/gin" |
| | | "github.com/h2non/filetype" |
| | | "go.uber.org/zap" |
| | | "net/http" |
| | | "srm/global" |
| | |
| | | // @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}" |
| | | // @Router /con/createContract [post] |
| | | func (conApi *ContractApi) CreateContract(c *gin.Context) { |
| | | name := c.Param("name") |
| | | name := c.PostForm("name") |
| | | file, err := c.FormFile("file") |
| | | if err != nil { |
| | | c.JSON(400, gin.H{"error": err.Error()}) |
| | |
| | | defer f.Close() |
| | | f.Read(fileContent) |
| | | |
| | | // 重置文件指针 |
| | | f.Seek(0, 0) |
| | | |
| | | // 使用 filetype 库检测文件类型 |
| | | kind, _ := filetype.Match(fileContent) |
| | | if kind == filetype.Unknown { |
| | | c.JSON(http.StatusBadRequest, gin.H{"error": "Unknown file type"}) |
| | | return |
| | | } |
| | | |
| | | contract := test.Contract{ |
| | | FileName: name, |
| | | FileContent: fileContent, |
| | | FileType: kind.MIME.Value, |
| | | } |
| | | |
| | | if err, id := conService.CreateContract(&contract); err != nil { |
| | |
| | | response.FailWithMessage("创建失败", c) |
| | | } else { |
| | | //response.OkWithMessage("创建成功", c) |
| | | response.OkWithData(gin.H{"id": id}, c) |
| | | response.OkWithData(gin.H{"id": id, "name": name}, c) |
| | | } |
| | | } |
| | | |
| | |
| | | //reader := bytes.NewReader(contract.FileContent) |
| | | //c.DataFromReader(http.StatusOK, int64(len(contract.FileContent)), "application/pdf", reader, map[string]string{"Content-Disposition": fmt.Sprintf("attachment; filename=%s", contract.FileName)}) |
| | | reader := bytes.NewReader(contract.FileContent) |
| | | c.Writer.Header().Set("Content-Type", "application/pdf") |
| | | c.Header("Content-Type", contract.FileType) |
| | | c.Writer.Header().Set("Content-Disposition", "inline; filename="+contract.FileName) |
| | | http.ServeContent(c.Writer, c.Request, contract.FileName, time.Now(), reader) |
| | | } |
| | |
| | | c.Header("Content-Description", "File Transfer") |
| | | c.Header("Content-Transfer-Encoding", "binary") |
| | | c.Header("Content-Disposition", fmt.Sprintf("attachment; filename=%s", contract.FileName)) |
| | | c.Header("Content-Type", "application/pdf") |
| | | c.Header("Content-Type", contract.FileType) |
| | | |
| | | // 将文件作为响应体发送 |
| | | http.ServeContent(c.Writer, c.Request, contract.FileName, time.Now(), reader) |