Skip to content

Set MIME type for files requested via raw api #9305

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
1 change: 1 addition & 0 deletions routers/api/v1/repo/file.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ func GetRawFile(ctx *context.APIContext) {
}
return
}
ctx.Context.Data["IsRawApi"] = true
if err = repo.ServeBlob(ctx.Context, blob); err != nil {
ctx.Error(http.StatusInternalServerError, "ServeBlob", err)
}
Expand Down
15 changes: 13 additions & 2 deletions routers/repo/download.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@ package repo
import (
"fmt"
"io"
"mime"
"path"
"path/filepath"
"strings"

"code.gitea.io/gitea/modules/base"
Expand All @@ -21,7 +23,10 @@ import (
// ServeData download file from io.Reader
func ServeData(ctx *context.Context, name string, reader io.Reader) error {
buf := make([]byte, 1024)
n, _ := reader.Read(buf)
n, err := reader.Read(buf)
if err != nil && err != io.EOF {
return err
}
if n >= 0 {
buf = buf[:n]
}
Expand All @@ -40,7 +45,13 @@ func ServeData(ctx *context.Context, name string, reader io.Reader) error {
ctx.Resp.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, name))
}

_, err := ctx.Resp.Write(buf)
if ctx.Data["IsRawApi"] == true {
if mimeType := mime.TypeByExtension(filepath.Ext(name)); mimeType != "" {
ctx.Resp.Header().Set("Content-Type", mimeType)
}
}

_, err = ctx.Resp.Write(buf)
if err != nil {
return err
}
Expand Down