mirror of
https://git.rwth-aachen.de/acs/public/villas/web-backend-go/
synced 2025-03-30 00:00:12 +01:00
simplify download function for files
This commit is contained in:
parent
cb43c25c27
commit
0e54b7ba33
1 changed files with 8 additions and 12 deletions
|
@ -22,12 +22,12 @@
|
||||||
package file
|
package file
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
"io/ioutil"
|
"io/ioutil"
|
||||||
"mime/multipart"
|
"mime/multipart"
|
||||||
"os"
|
"net/http"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
|
"strconv"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"git.rwth-aachen.de/acs/public/villas/web-backend-go/database"
|
"git.rwth-aachen.de/acs/public/villas/web-backend-go/database"
|
||||||
|
@ -57,20 +57,16 @@ func (f *File) save() error {
|
||||||
|
|
||||||
func (f *File) download(c *gin.Context) error {
|
func (f *File) download(c *gin.Context) error {
|
||||||
|
|
||||||
err := ioutil.WriteFile(f.Name, f.FileData, 0644)
|
// create unique file name
|
||||||
if err != nil {
|
filename := "file_" + strconv.FormatUint(uint64(f.ID), 10) + "_" + f.Name
|
||||||
return fmt.Errorf("file could not be temporarily created on server disk: %s", err.Error())
|
// detect the content type of the file
|
||||||
}
|
contentType := http.DetectContentType(f.FileData)
|
||||||
defer os.Remove(f.Name)
|
|
||||||
//Seems this headers needed for some browsers (for example without this headers Chrome will download files as txt)
|
//Seems this headers needed for some browsers (for example without this headers Chrome will download files as txt)
|
||||||
c.Header("Content-Description", "File Transfer")
|
c.Header("Content-Description", "File Transfer")
|
||||||
c.Header("Content-Transfer-Encoding", "binary")
|
c.Header("Content-Disposition", "attachment; filename="+filename)
|
||||||
c.Header("Content-Disposition", "attachment; filename="+f.Name)
|
c.Data(http.StatusOK, contentType, f.FileData)
|
||||||
//c.Header("Content-Type", contentType)
|
|
||||||
c.File(f.Name)
|
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *File) register(fileHeader *multipart.FileHeader, objectType string, objectID uint) error {
|
func (f *File) register(fileHeader *multipart.FileHeader, objectType string, objectID uint) error {
|
||||||
|
|
Loading…
Add table
Reference in a new issue