我正在开发一个使用图片上传功能的应用程序。应用程序后端是在Golang中编写的,其中前端位于Angular4中。我正在使用Gin框架在Golang中运行http请求。
以下是上传图片的Golang代码:
var popup = new ol.Overlay.Popup();
map.addOverlay(popup);
前端和后端也位于具有子域的同一域中。当请求从前端生成时。
我在Golang代码中传递了以下标题:
func UploadFile(c *gin.Context){
imageData := make(map[string]interface{})
response := ResponseController{}
/* ------ Get current date ------ */
currDate := time.Now().UTC()
yearString := strconv.Itoa(currDate.Year())
monthString := strconv.Itoa(int(currDate.Month()))
dayString := strconv.Itoa(currDate.Day())
path := config.UploadBasePath+config.AppFolder+config.UploadsFolder+yearString+"/"+monthString+"/"+dayString+"/"
/* create temp directory if does not exist */
if _, err := os.Stat(path); os.IsNotExist(err) {
os.MkdirAll(path, 0755)
}
/* read data from form */
file, err := c.FormFile("file")
if err != nil {
response = ResponseController{
config.FailureCode,
config.FailureFlag,
"Error while reading image.",
nil,
}
GetResponse(c, response)
return
}
filePath := path+file.Filename
if err := c.SaveUploadedFile(file, filePath); err != nil {
response = ResponseController{
config.FailureCode,
config.FailureFlag,
"Error while uploading image.",
err,
}
GetResponse(c, response)
return
}
uploadUrl := "/"+config.UploadsFolder+yearString+"/"+monthString+"/"+dayString+"/"+file.Filename
imageData["upload_url"] = uploadUrl
response = ResponseController{
config.SuccessCode,
config.SuccessFlag,
"Image uploaded successfully.",
imageData,
}
GetResponse(c, response)
}
当我上传图片时,它会在控制台中返回以下错误,图片无法上传:
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
任何人都可以指导我在这里缺少的东西。谢谢!
答案 0 :(得分:0)
尝试在路由器中设置OPTIONS
router.HandleFunc("/", getModulos).Methods("POST", "GET", "OPTIONS")
您可以将CONTENT-TYPE
设置为w.Header().Set("Access-Control-Allow-Headers", "Content-Type")