英文:
Having trouble uploading files from Javascript and receiving it through Go
问题
我使用Axios在JavaScript中设置了一个简单的前端服务。该服务接收一个文件列表,并使用POST请求将其发送到我的服务器代码。我的JavaScript代码如下:
const testPost = async (files) => {
let formData = new FormData();
files.forEach((file) => {
formData.append("file", file);
});
const res = await axios({
method: "POST",
url: baseUrl,
data: formData,
headers: {
"Content-Type": "multipart/form-data",
},
});
return res;
};
我的Go代码如下:
func (h *SendHandler) TestPost(w http.ResponseWriter, r *http.Request) {
// 允许跨域请求
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
formdata := r.MultipartForm
fmt.Println(formdata)
}
我认为问题出在我的Go代码的TestPost函数的主体部分。当我在前端代码中点击发送后,我收到了一个响应。但是在我的Go函数中,当我打印formdata时,输出为<nil>
。我希望能够访问列表中的每个文件,但我甚至无法访问formdata。我对Web开发和Go都还很陌生,所以肯定有些地方我理解错了。有什么建议吗?
英文:
I set up a simple frontend service in JavaScript using Axios. This service takes a list of files and sends to my server code using a post request. My JavaScript looks like this
const testPost = async (files) => {
let formData = new FormData();
files.forEach((file) => {
formData.append("file", file);
});
const res = await axios({
method: "POST",
url: baseUrl,
data: formData,
headers: {
"Content-Type": "multipart/form-data",
},
});
return res;
};
And my Go code looks like this:
func (h *SendHandler) TestPost(w http.ResponseWriter, r *http.Request) {
//Allow CORS here By * or specific origin
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
formdata := r.MultipartForm
fmt.Println(formdata)
}
I think my problem lies in the body of my TestPost function in Go because I click send in my frontend code, I receive a response. In my Go function, when I print my formdata, it outputs <nil>
. I want to be able to access each file in the list but I can't even access the formdata. I'm still new to both web dev and Go so there is definitely something I am misunderstanding here. Any pointers?
答案1
得分: 1
MultipartForm的文档中提到:
MultipartForm是解析后的多部分表单,包括文件上传。只有在调用ParseMultipartForm之后,该字段才可用。
通过在使用r.MultipartForm
之前调用ParseMultipartForm来修复。
err := r.ParseMultipartForm(maxMemory)
if err != nil {
http.Error(w, "Bad Request", http.StatusBadRequest)
return
}
// 现在r.MultipartForm已设置。
fmt.Println(r.MultipartForm) // 不会打印nil
英文:
The documentation for MultipartForm says:
> MultipartForm is the parsed multipart form, including file uploads. This field is only available after ParseMultipartForm is called.
Fix by calling ParseMultipartForm before using r.MultipartForm
.
err := r.ParseMultipartForm(maxMemory)
if err != nil {
http.Error(w, "Bad Request", http.StatusBadRequest)
return
}
// r.MultipartForm is now set.
fmt.Println(r.MultipartForm) // does not print nil
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论