zoukankan      html  css  js  c++  java
  • Go gin之文件上传

    话不多说,代码如下

    package api

    import (
    "net/http"
    "github.com/gin-gonic/gin"
    "go-admin/pkg/app"
    "go-admin/pkg/e"
    "go-admin/pkg/logging"
    "go-admin/pkg/upload"
    )

    // @Summary Import Image
    // @Produce json
    // @Param image formData file true "Image File"
    // @Success 200 {object} app.Response
    // @Failure 500 {object} app.Response
    // @Router /api/v1/tags/import [post]
    func UploadImage(c *gin.Context) {
    appG := app.Gin{C: c}
    file, image, err := c.Request.FormFile("image")
    if err != nil {
    logging.Warn(err)
    appG.Response(http.StatusInternalServerError, e.ERROR, nil)
    return
    }

    if image == nil {
    appG.Response(http.StatusBadRequest, e.INVALID_PARAMS, nil)
    return
    }

    imageName := upload.GetImageName(image.Filename)
    fullPath := upload.GetImageFullPath()
    savePath := upload.GetImagePath()
    src := fullPath + imageName
    c.JSON(200, gin.H{
    "debug":"错误调试",
    "imageName": imageName,
    "savePath": savePath,
    "src": src,
    })


    if !upload.CheckImageExt(imageName) || !upload.CheckImageSize(file) {
    appG.Response(http.StatusBadRequest, e.ERROR_UPLOAD_CHECK_IMAGE_FORMAT, nil)
    return
    }

    err = upload.CheckImage(fullPath)
    if err != nil {
    logging.Warn(err)
    appG.Response(http.StatusInternalServerError, e.ERROR_UPLOAD_CHECK_IMAGE_FAIL, nil)
    return
    }

    if err := c.SaveUploadedFile(image, src); err != nil {
    logging.Warn(err)
    appG.Response(http.StatusInternalServerError, e.ERROR_UPLOAD_SAVE_IMAGE_FAIL, nil)
    return
    }

    appG.Response(http.StatusOK, e.SUCCESS, map[string]string{
    "image_url": upload.GetImageFullUrl(imageName),
    "image_save_url": savePath + imageName,
    })
    }


    注意:需要配置文件上传大小、允许上传类型,否则报错

  • 相关阅读:
    [苹果maccms] MACCMS苹果cms宝塔定时任务添加教程说明
    [苹果cmsV10]新版本演员库分类报无权限问题和解决方法!
    CentOS 6.8安装Python2.7.13
    [HOWTO] Install Sphinx for A Script Pro
    A Script Pro nginx URL重写规则无法播放MP4解决方法
    随机跳转
    UI库
    vuex
    vue 数据请求
    vue守卫、储存与路由模式
  • 原文地址:https://www.cnblogs.com/ztshuai/p/12568388.html
Copyright © 2011-2022 走看看