A recent requirement is to export data to a file in a specified format. The browser downloads the generated file, usually returning the static file address directly to the server. The front end uses the tag to point to the address with the href attribute. Xes (an extension of XML) and image formats like PNG. The following is a summary of some solutions.

Because there are large files, no writes are streamed to the front end.

use<a>Of the labeldownloadattribute

The <a> tag’s dowanLoad attribute only works with the same source and currently only works with Firefox and Google Chrome

The href attribute must be set in the tag. The Download property specifies the destination of the hyperlink to be downloaded. This property can also set a value to specify the name of the downloaded file. There is no limit to the values allowed, and the browser will automatically detect the correct file extensions and add them to files (.img,.pdf,.txt,.html, etc.).

// Please change the href address to ceshi
<a href="www.baidu.com" download="ceshi">
Copy the code

Ctx.sendfile () method for the Iris framework

The IRIS framework has a wrapper method ctx.sendFile () that returns the contents of the file to the front end. (PS: If the file is very large, it still feels inconvenient to have a lot of content)

SendFile(filename string, destinationName string) error
Copy the code

Filename is the destination file path and destinationName is the endowed filename

/* The file directory is -- files -- first.xml -- main.go */
package main

import (
    "github.com/kataras/iris"
)

func main(a) {
    app := iris.New()
    app.Get("/".func(ctx iris.Context) {
        file := "./files/first.xml"
        ctx.SendFile(file, "c.xml")
    })
    app.Run(iris.Addr(": 8080"))}Copy the code

Compress specified files

You can compress a file that cannot be downloaded by the browser into a. Zip file and return the file to the browser for download. I use this method

/* The compressed file is in zip format. * filePath indicates the path of the compressed file, and zipPath indicates the path of the compressed file
func FileToZip(filePath string,zipPath string) error {
	f,err := os.Open(filePath)
	iferr ! =nil{
		return err
	}
	defer f.Close()

	z,err := os.Create(zipPath)
	iferr ! =nil{
		return err
	}
	defer z.Close()

	wr := zip.NewWriter(z)
	// Since filePath is a path, all folders in the path are created
	w,err := wr.Create(filePath)
	iferr ! =nil{
		return err
	}
	_,err = io.Copy(w,f)
	iferr ! =nil{
		return err
	}
	return nil
}
Copy the code

The above three methods are through baidu and their own understanding of the summary of the method, if there is no please big guy correct, if there are other better methods please give advice 🙂