github.com/wangyougui/gf/v2@v2.6.5/os/gres/gres_file.go (about)

     1  // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
     2  //
     3  // This Source Code Form is subject to the terms of the MIT License.
     4  // If a copy of the MIT was not distributed with this file,
     5  // You can obtain one at https://github.com/wangyougui/gf.
     6  
     7  package gres
     8  
     9  import (
    10  	"archive/zip"
    11  	"bytes"
    12  	"io"
    13  	"os"
    14  
    15  	"github.com/wangyougui/gf/v2/internal/json"
    16  )
    17  
    18  type File struct {
    19  	file     *zip.File
    20  	reader   *bytes.Reader
    21  	resource *Resource
    22  }
    23  
    24  // Name returns the name of the file.
    25  func (f *File) Name() string {
    26  	return f.file.Name
    27  }
    28  
    29  // Open returns a ReadCloser that provides access to the File's contents.
    30  // Multiple files may be read concurrently.
    31  func (f *File) Open() (io.ReadCloser, error) {
    32  	return f.file.Open()
    33  }
    34  
    35  // Content returns the content of the file.
    36  func (f *File) Content() []byte {
    37  	reader, err := f.Open()
    38  	if err != nil {
    39  		return nil
    40  	}
    41  	defer reader.Close()
    42  	buffer := bytes.NewBuffer(nil)
    43  	if _, err = io.Copy(buffer, reader); err != nil {
    44  		return nil
    45  	}
    46  	return buffer.Bytes()
    47  }
    48  
    49  // FileInfo returns an os.FileInfo for the FileHeader.
    50  func (f *File) FileInfo() os.FileInfo {
    51  	return f.file.FileInfo()
    52  }
    53  
    54  // Export exports and saves all its sub files to specified system path `dst` recursively.
    55  func (f *File) Export(dst string, option ...ExportOption) error {
    56  	return f.resource.Export(f.Name(), dst, option...)
    57  }
    58  
    59  // MarshalJSON implements the interface MarshalJSON for json.Marshal.
    60  func (f File) MarshalJSON() ([]byte, error) {
    61  	info := f.FileInfo()
    62  	return json.Marshal(map[string]interface{}{
    63  		"name": f.Name(),
    64  		"size": info.Size(),
    65  		"time": info.ModTime(),
    66  		"file": !info.IsDir(),
    67  	})
    68  }