MCPcopy
hub / github.com/IceWhaleTech/CasaOS / GetDownloadSingleFile

Function GetDownloadSingleFile

route/v1/file.go:225–271  ·  view source on GitHub ↗
(ctx echo.Context)

Source from the content-addressed store, hash-verified

223}
224
225func GetDownloadSingleFile(ctx echo.Context) error {
226 filePath := ctx.QueryParam("path")
227 if len(filePath) == 0 {
228 return ctx.JSON(common_err.CLIENT_ERROR, model.Result{
229 Success: common_err.INVALID_PARAMS,
230 Message: common_err.GetMsg(common_err.INVALID_PARAMS),
231 })
232 }
233 fileName := path.Base(filePath)
234 // c.Header("Content-Disposition", "inline")
235 ctx.Request().Header.Add("Content-Disposition", "attachment; filename*=utf-8''"+url2.PathEscape(fileName))
236
237 fi, err := os.Open(filePath)
238 if err != nil {
239 panic(err)
240 }
241
242 // We only have to pass the file header = first 261 bytes
243 buffer := make([]byte, 261)
244
245 _, _ = fi.Read(buffer)
246
247 kind, _ := filetype.Match(buffer)
248 if kind != filetype.Unknown {
249 ctx.Request().Header.Add("Content-Type", kind.MIME.Value)
250 }
251 node, err := os.Stat(filePath)
252 // Set the Last-Modified header to the timestamp
253 ctx.Request().Header.Add("Last-Modified", node.ModTime().UTC().Format(http.TimeFormat))
254
255 knownSize := node.Size() >= 0
256 if knownSize {
257 ctx.Request().Header.Add("Content-Length", strconv.FormatInt(node.Size(), 10))
258 }
259 http.ServeContent(ctx.Response().Writer, ctx.Request(), fileName, node.ModTime(), fi)
260 defer fi.Close()
261 fileTmp, err := os.Open(filePath)
262 if err != nil {
263 return ctx.JSON(common_err.SERVICE_ERROR, model.Result{
264 Success: common_err.FILE_DOES_NOT_EXIST,
265 Message: common_err.GetMsg(common_err.FILE_DOES_NOT_EXIST),
266 })
267 }
268 defer fileTmp.Close()
269
270 return nil
271}
272
273// @Summary 获取目录列表
274// @Produce application/json

Callers

nothing calls this directly

Calls 5

GetMsgFunction · 0.92
RequestMethod · 0.80
ReadMethod · 0.80
CloseMethod · 0.80
ModTimeMethod · 0.65

Tested by

no test coverage detected