为了账号安全,请及时绑定邮箱和手机立即绑定

在Golang中编辑ZIP存档

在Golang中编辑ZIP存档

Go
吃鸡游戏 2022-09-05 10:24:55
我正在编写一个应用程序,允许用户将匿名数据上传到S3存储桶,以便允许他们在不向我们提供身份验证数据的情况下试用我们的产品。这是处理ZIP存档的结构,这些存档已被证明是正确的:type ZipWriter struct {    buffer *bytes.Buffer    writer *zip.Writer}func FromFile(file io.Reader) (*ZipWriter, error) {    // First, read all the data from the file; if this fails then return an error    data, err := ioutil.ReadAll(file)    if err != nil {        return nil, fmt.Errorf("Failed to read data from the ZIP archive")    }    // Next, put all the data into a buffer and then create a ZIP writer    // from the buffer and return that writer    buffer := bytes.NewBuffer(data)    return &ZipWriter{        buffer: buffer,        writer: zip.NewWriter(buffer),    }, nil}// WriteToStream writes the contents of the ZIP archive to the provided streamfunc (writer *ZipWriter) WriteToStream(file io.Writer) error {    // First, attempt to close the ZIP archive writer so that we can avoid    // double writes to the underlying buffer; if an error occurs then return it    if err := writer.writer.Close(); err != nil {        return fmt.Errorf("Failed to close ZIP archive, error: %v", err)    }    // Next, write the underlying buffer to the provided stream; if this fails    // then return an error    if _, err := writer.buffer.WriteTo(file); err != nil {        return fmt.Errorf("Failed to write the ZIP data to the stream, error: %v", err)    }    return nil}我遇到的问题是,尽管上传到S3成功,但当下载ZIP存档并提取数据时,找不到任何文件。在调查此问题时,我提出了许多可能的故障点:FromFile不会从文件正确创建ZIP存档;导致存档文件损坏。WriteToStream在写入存档时损坏数据。这似乎不太可能,因为我已经用a作为读者测试了此功能。除非 a 生成损坏的 ZIP 存档,否则当没有,我认为此功能可能按预期工作。bytes.Bufferos.Filebytes.Buffer数据写入 S3 时已损坏。这似乎不太可能,因为我已将此代码用于其他数据而没有问题。因此,除非ZIP存档具有需要与其他文件类型区别对待的结构,否则我在这里也没有看到问题。DoRequest在更深入地研究了这些可能性之后,我认为问题可能出在我如何从存档文件创建ZIP编写器,但我不确定问题是什么。
查看完整描述

1 回答

?
胡说叔叔

TA贡献1804条经验 获得超8个赞

这里的问题是一个红鲱鱼。正如@CeriseLimón指出的那样,调用和打开现有的ZIP存档必然会导致将空存档添加到文件的末尾。在我的用例中,解决方案是打开文件并将其直接写入流,而不是尝试将其作为ZIP存档读取。NewWriterClose


file, err := os.Open(location)

if err != nil {

    log.Fatalf("Unable to open ZIP archive located in %s, error: %v", location, err)

}


if body, err := DoRequest(new(http.Client), http.MethodPut, url, "", file); err != nil {

    log.Fatalf("Failed to upload the data to S3, response: %s, error: %v", string(body), err)

}


查看完整回答
反对 回复 2022-09-05
  • 1 回答
  • 0 关注
  • 83 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信