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

我的文件系统的目录如下。


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


至尊宝的传说
浏览 211回答 2
2回答

跃然一笑

http.Dir(uploadPath)是从string到http.Dir的显式类型转换,它只是一个带有Open方法的字符串。这意味着不对字符串进行任何处理,您可以filepath.Join直接对原始字符串进行处理:filePath := filepath.Join(uploadPath, fileName)注意:您用于http.Dir将参数转换为的原因http.FileServer是Dir.Open实现http.Filesystem接口的方法。

幕布斯6054654

因为我在 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 的提示。
打开App,查看更多内容
随时随地看视频慕课网APP