使用Fetch API在Golang中上传图片遇到问题
你的问题出在两个核心点上:
1. 前端Fetch请求未按multipart/form-data格式发送文件
直接把File对象作为fetch的body发送时,浏览器不会自动将请求包装成multipart/form-data格式,反而会把Content-Type设置为文件本身的MIME类型(比如image/png),这就导致Golang服务器报错request Content-Type isn't multipart/form-data,自然无法通过r.FormFile("file")读取文件。
同时,前端用response.json()解析服务器返回的纯文本错误信息,就会触发SyntaxError: Unexpected token r in JSON at position 0。
修正前端代码:使用FormData包装文件,且不要手动设置Content-Type(浏览器会自动添加正确的multipart/form-data头及边界标识):
const uploadFile = (file) => { const formData = new FormData(); formData.append('file', file); // 这里的"file"要和服务器端r.FormFile的参数一致 fetch('/upload', { method: 'POST', body: formData // 发送FormData对象 }).then(response => { // 先判断响应状态,避免解析非JSON错误文本 if (!response.ok) { return response.text().then(err => Promise.reject(err)); } return response.json(); }).then(success => { console.log(success); }).catch(error => { console.log(error); }); };
2. 后端jsonResponse函数返回非合法JSON
当前jsonResponse直接输出字符串(比如"File uploaded successfully!."),这不是合法的JSON格式,前端用response.json()解析时同样会出错。
修正后端代码:将返回内容包装成标准JSON对象:
func jsonResponse(w http.ResponseWriter, code int, message string) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(code) fmt.Fprintf(w, `{"message": "%s"}`, message) // 输出JSON格式字符串 }
另外,你的UploadFile函数里漏了导入os包,需要在import块中补充:
import ( // ... 其他已导入的包 "os" )
验证修正效果
修改后,前端选择文件发送的请求会自动带上正确的Content-Type: multipart/form-data; boundary=xxx头,服务器端r.FormFile("file")能正常读取文件,同时返回的JSON格式响应也能被前端正确解析。
内容的提问来源于stack exchange,提问作者phantom_wizard

