【问题标题】:Corrupted zip file is sent in golang REST API在 golang REST API 中发送损坏的 zip 文件
【发布时间】:2023-01-31 05:18:12
【问题描述】:

我已经搜索了很多有关此问题的信息,但找不到合适的解决方案。 我想从 mongodb 集合中找到一些记录并将每条记录保存到一个 json 文件,然后将它们压缩并作为 REST API 的响应发回。

    // each record should be saved in a file
    var records []iodefRepo.IodefRecord
    if cur, err := h.iodefRepo.IodefCollection().Find(helper.Context(), filter, options.Find().SetSort(M{"received_at": -1})); err != nil {
        return helper.WrapInternalErr("while finding iodef, err=" + err.Error())
    } else if err := cur.All(helper.Context(), &records); err != nil {
        return helper.WrapInternalErr("while un-cursoring records, err=" + err.Error())
    }

    -------------------------------------------------------
    resultFile, err := os.Create(fmt.Sprint(fileName, ".zip"))
    if err != nil {
        return helper.WrapInternalErr("while creating the result file, err=" + err.Error())
    }

    writer := zip.NewWriter(resultFile)
    // files is a [][]byte that each element is []byte of json.Unmarshal
    for i, f := range files {
        if file, err := writer.Create(fmt.Sprint("IncidentName=", records[i].Document.Incidents[0].IncidentID.Name, ", IncidentData=", records[i].Document.Incidents[0].IncidentID.Data, ".", format)); err != nil {
            return helper.WrapInternalErr("while creating iodef file, err=" + err.Error())
        } else if _, err := file.Write(f); err != nil {
            return helper.WrapInternalErr("while writing to iodef file, err=" + err.Error())
        }
    }

    helper.AddResponseHeader("Content-Type", "application/zip")
    helper.AddResponseHeader("Content-Transfer-Encoding", "binary")
    helper.AddResponseHeader("Content-Disposition", "attachment; filename=export.zip")

    _ = writer.Close()
    _ = resultFile.Close()

    if result, err := os.ReadFile(fileName + ".zip"); err != nil {
        return helper.WrapInternalErr("while reading zip file, err=" + err.Error())
    } else {
        // this result which is a []byte will be write to standard ResponseWriter
        // the same as err := w.Write(result); mention that I have ckecked and there
        // is no error in any of the steps and everything is done without any errors.
        return helper.WrapOk(result)
    }
    

我在服务器上生成后保存 zip 文件并测试它,它工作得很好但是当我在邮递员中读取响应并将其另存为 zip 文件时,文件已损坏,我不知道为什么而且我没有任何解决问题的线索,有类似的问题,但没有一个有效。 postman 中 API 的响应大小与服务器端生成的文件大小完全相同。

我确实尝试了一些东西,例如使用不同的标头和不同的方法来读取结果 zip 文件,但都没有用,我认为 os.ReadFile 是完全读取二进制文件的最佳选择。 我不知道为什么存在这个问题。 只是想强调一下,生成的 zip 文件在服务器端正常工作,在使用 os.ReadFile 和标准 http.ResponseWriter.Write 将其作为二进制数组发送后,文件将无法正常工作。

【问题讨论】:

  • 可能并非所有文件系统都允许使用等号 = 和逗号 ,。所以一定要尝试使用“正常”、简单的名称。
  • @icza 实际上这不是问题,因为我正在测试服务器的客户端机器具有完全相同的操作系统,我什至在本地主机上测试了 API,但问题仍然存在。

标签: rest go zip


【解决方案1】:

最后我找到了答案,我仍然不知道我以前的解决方案有什么问题,但是当我使用http.ServeFile(w, r, "/path/to/zip_file")函数而不是使用ResponseWriter.Write(fileBytes)时,问题就解决了。使用ResponseWriter.Write(fileBytes) 可能会导致问题,这实际上很奇怪。如果有人知道为什么会这样,请告诉我。 谢谢。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-23
    • 2020-02-22
    • 1970-01-01
    • 2015-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多