我正在尝试使用多部分形式将音频文件上传到 Golang 服务器。但是,Go 返回错误:
multipart: NextPart: bufio: buffer full
我相信这表明我的 Javascript 请求中存在不符合多部分格式的内容。这是我的 Javascript:
function UploadFile(file) {
var xhr = new XMLHttpRequest();
if (file.type == "audio/mpeg" && file.size <= $id("MAX_FILE_SIZE").value) {
// start upload
var boundary = '---------------------------' + Math.floor(Math.random()*32768) + Math.floor(Math.random()*32768) + Math.floor(Math.random()*32768);
xhr.open("POST", $id("upload").action, true);
xhr.setRequestHeader("Content-Type", "multipart/form-data; boundary=" + boundary);
xhr.setRequestHeader("X_FILENAME", file.name);
xhr.send(file);
}
}
这是我的 Golang 服务器处理程序:
func FileHandler(w http.ResponseWriter, r *http.Request) {
var (
status int
err error
)
defer func() {
if nil != err {
http.Error(w, err.Error(), status)
}
}()
// parse request with maximum memory of _24Kilobits
const _24K = (1 << 20) * 24
if err = r.ParseMultipartForm(_24K); nil != err {
fmt.Println(err)
status = http.StatusInternalServerError
return
}
for _, fheaders := range r.MultipartForm.File {
for _, hdr := range fheaders {
// open uploaded
var infile multipart.File
if infile, err = hdr.Open(); nil != err {
status = http.StatusInternalServerError
return
}
// open destination
var outfile *os.File
if outfile, err = os.Create("./uploaded/" + hdr.Filename); nil != err {
status = http.StatusInternalServerError
return
}
// 32K buffer copy
var written int64
if written, err = io.Copy(outfile, infile); nil != err {
status = http.StatusInternalServerError
return
}
w.Write([]byte("uploaded file:" + hdr.Filename + ";length:" + strconv.Itoa(int(written))))
}
}
}
如果有人知道我为什么会收到此错误,我将不胜感激。
最佳答案
在与 Ajax 请求进行了长期艰苦的斗争之后,我让它发送了正确的信息。这是我使用的代码:
var xhr = new XMLHttpRequest(),
boundary=Math.random().toString().substr(2);
var formdata = new FormData();
formdata.append("file", file);
xhr.open("POST", $id("upload").action, true);
//xhr.setRequestHeader("content-type", "multipart/form-data; charset=utf-8; boundary=" + boundary);
xhr.send(formdata);
请注意标题不再使用,我发现您可以比任何其他方法更容易地将数据附加到表单数据,例如:How to send multipart/form-data form content by ajax (no jquery)?
关于javascript - Ajax 将内容类型为 Multipart 的文件上传到 GoLang 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25493706/