gpt4 book ai didi

rest - 文件上传后为空响应

转载 作者:IT王子 更新时间:2023-10-29 00:47:01 26 4
gpt4 key购买 nike

我在 Go 中编写了一个小型 REST api,我正在使用相同的函数返回带有状态代码和消息的 http.Response:

type apiResponse struct {
Status int `json:"status"`
Message string `json:"message"`
}

我正在将其编码为 json 字符串并使用 w.Write() 将其放入响应中。

该 API 具有三个端点,其中之一允许用户上传文件。两个工作非常好,我得到了我期望的回应。上传端点返回一个有效响应,其中的 Content-Length 与我期望的消息匹配,但是当我读取它时(使用 ioutil.ReadAll),它是空的!

我做错了什么?

这是读取正文的函数:

func readResponseContent(resp *http.Response) string {
defer resp.Body.Close()
fmt.Println(resp)
fmt.Println(resp.ContentLength)
bodyBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println("Error in response: %s", err.Error())
os.Exit(1)
}
bodyString := string(bodyBytes)
return bodyString
}

这是处理程序:

func handleSubmission(w http.ResponseWriter, r *http.Request) {

var Buf bytes.Buffer
file, header, err := r.FormFile(audioUploadKey)

if err != nil {
log.Printf("Error uploading file: %s\n", err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer file.Close()

jobID, _ := uuid.NewUUID()
_ = os.MkdirAll(path.Join(jobsPath, jobID.String()), 0750)

log.Printf("Received file %s\n", header.Filename)

io.Copy(&Buf, file)
fileOut, _ := os.Create(path.Join(jobsPath, jobID.String(),

Buf.WriteTo(fileOut)
Buf.Reset()

// submit
// DO STUFF with jobID

apiResp := apiResponse{Status:http.StatusCreated, Message:jobID.String()}
jsonResp, _ := json.Marshal(apiResp)
writeJSONResponse(w, jsonResp)
return}

最佳答案

问题看起来你忘记了你收到的表单的内容类型,当你发送 json 时,内容类型是 application/json,当你上传文件时,你应该使用 multipart/form-data,如果是这样的话,您可以这样阅读它:

    import(
"ioutil"
"net/http"
)
//check all posible errors, I´m assuming you just have one file per key
func handler(w http.ResponseWriter, r *http.Request) {
r.ParseMultipartForm(1000000) //1 MB in memory, the rest in disk
datas := r.MultipartForm
for k, headers := range datas.File {
auxiliar, _ := headers[0].Open() //first check len(headers) if it's correct
fileName:=headers[0].Filename
file, _ := ioutil.ReadAll(auxiliar)
// do what you need to do with the file
}
}
at the frontEnd you should have some javascript like this:

function handleFile(url,file){
let data=new FormData();
data.append("key",file); //this is the key when ranging over map at backEnd
fetch(url,{method:"PUT",body:data})
}

关于rest - 文件上传后为空响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49778912/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com