Golang Gin 框架下载远程图片到本地文件夹
可以使用 Golang 的 net/http 包下载远程图片,然后使用 os 包保存到本地文件夹中。下面是一个使用 Gin 框架实现的示例代码:
package main
import (
"fmt"
"io"
"net/http"
"os"
"github.com/gin-gonic/gin"
)
func main() {
router := gin.Default()
router.GET("/download", func(c *gin.Context) {
url := c.Query('url')
filename := c.Query('filename')
if url == "" || filename == "" {
c.JSON(http.StatusBadRequest, gin.H{
'error': 'url or filename is missing',
})
return
}
resp, err := http.Get(url)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
'error': 'failed to download image',
})
return
}
defer resp.Body.Close()
file, err := os.Create(filename)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
'error': 'failed to create file',
})
return
}
defer file.Close()
_, err = io.Copy(file, resp.Body)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
'error': 'failed to save image',
})
return
}
c.JSON(http.StatusOK, gin.H{
'message': fmt.Sprintf('image downloaded to %s', filename),
})
})
router.Run(":8080")
}
在浏览器中访问 http://localhost:8080/download?url=远程图片url&filename=本地文件名 即可下载远程图片到本地文件夹中。
原文地址: https://www.cveoy.top/t/topic/lCtG 著作权归作者所有。请勿转载和采集!