这是一个前后端分离的项目,gin+vue2, 我在后端配置了跨域
func main() {
r := gin.Default()
// 跨域中间件
r.Use(func (c *gin.Context) {
c.Header("Access-Control-Allow-Origin", "*")
c.Header("Access-Control-Allow-Headers", "Content-Type,X-CSRF-Token, Authorization")
c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PATCH, PUT")
c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type")
c.Header("Access-Control-Allow-Credentials", "true")
c.Header("Content-Disposition", "attachment;filename=test.png")
if method == "OPTIONS" {
c.AbortWithStatus(http.StatusNoContent)
return
}
c.Next()
})
// r.Static("/static", "./storage/upload")
r.NoRoute(func(c *gin.Context) {
fullPath := c.Request.URL.String()
// 提取文件地址
path := file.GetFilePath(fullPath)
// 文件是一定存在的,直接在浏览器输入链接,可以成功走到这块代码
if file.Exists(path) {
c.Header("Access-Control-Allow-Origin", "*")
c.Header("Access-Control-Allow-Headers", "Content-Type,X-CSRF-Token, Authorization")
c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PATCH, PUT")
c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type")
c.Header("Access-Control-Allow-Credentials", "true")
c.Header("Content-Disposition", "attachment;filename=test.png")
c.File(path)
return
}
})
r.Run(":8888")
}
在前端,直接用img标签可以正常显示,浏览器也可以正常访问,刚开始用a标签download,但是变成了页面打开,但是后来发现页面打开即表示跨域了,且download属性只能对同源文件
var x = new XMLHttpRequest()
x.open("GET", url, true)
x.responseType = "blob"
x.setRequestHeader("Access-Control-Allow-Origin", "*")
x.onload = function(e) {
var url = window.URL.createObjectURL(x.response)
var a = document.createElement("a")
a.href = url
a.download = fileName
a.click()
window.URL.revokeObjectURL(url)
}
x.send()
预检请求成功,但是文件出现了跨域
求问:
gin 该如何给图片资源设置header头信息呢,如果不想在nginx中设置header头,这种情况有什么处理方案
解决:
在这个问题比较重要的除了跨域的配置之外,设置这个参数很重要
c.Header("Content-Disposition", "attachment;filename=test.png")
Content-Disposition 属性配合a标签 target=”_blank” 可解决跨域
<a :href="url" download target="_blank">下载图片</a>
gin
跨域
静态资源
文件下载
Evn