为了账号安全,请及时绑定邮箱和手机立即绑定

文件上传如何获取http.Dir路径

文件上传如何获取http.Dir路径

Go
至尊宝的传说 2022-06-21 10:40:47
我的文件系统的目录如下。fs := http.FileServer(http.Dir(uploadPath))我想上传这个文件夹下的文件。func upload(ctx context.Context, w http.ResponseWriter, r *http.Request) error {    r.ParseMultipartForm(maxUploadSize)    _, file, err := r.FormFile("file")    if err != nil {        return web.NewRequestError(err, http.StatusBadRequest)    }    if file.Size > maxUploadSize {        return web.NewRequestError(err, http.StatusBadRequest)    }    fileName := filepath.Base(file.Filename)    filePath := filepath.Join(http.Dir(uploadPath), fileName) // I want to get dir path.    if err := saveUploadedFile(file, filePath); err != nil {        return web.NewRequestError(err, http.StatusInternalServerError)    }    return web.Respond(ctx, w, fileName, http.StatusOK)}func saveUploadedFile(file *multipart.FileHeader, dst string) error {    src, err := file.Open()    if err != nil {        return err    }    defer src.Close()    out, err := os.Create(dst)    if err != nil {        return err    }    defer out.Close()    _, err = io.Copy(out, src)    return err}但是http.Dir(uploadPath)不能加入fileName,我该如何解决?我的项目树。my-api |- uploadPath |- handler     |- my handler file |- test     |- my test file |- main
查看完整描述

2 回答

?
跃然一笑

TA贡献1826条经验 获得超6个赞

http.Dir(uploadPath)是从stringhttp.Dir的显式类型转换,它只是一个带有Open方法的字符串。

这意味着不对字符串进行任何处理,您可以filepath.Join直接对原始字符串进行处理:

filePath := filepath.Join(uploadPath, fileName)

注意:您用于http.Dir将参数转换为的原因http.FileServerDir.Open实现http.Filesystem接口的方法。


查看完整回答
反对 回复 2022-06-21
?
幕布斯6054654

TA贡献1876条经验 获得超7个赞

因为我在 dockerfile 中配置了我的根路径,所以有两种方法可以修复它。


// 1. hardcode the '/rootPath' same as the dockerfile configure.

filePath := filepath.Join("/rootPath", uploadPath, fileName)


// 2. Dynamically get the current root path.

ex, err := os.Executable()

if err != nil {

    ...

}

rootPath := filepath.Dir(ex)

filePath := filepath.Join(rootPath, uploadPath, fileName)

感谢 Marc 的提示。


查看完整回答
反对 回复 2022-06-21
  • 2 回答
  • 0 关注
  • 208 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信