第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

文件上傳如何獲取http.Dir路徑

文件上傳如何獲取http.Dir路徑

Go
至尊寶的傳說 2022-06-21 10:40:47
我的文件系統(tǒng)的目錄如下。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條經(jīng)驗 獲得超6個贊

http.Dir(uploadPath)是從stringhttp.Dir的顯式類型轉(zhuǎn)換,它只是一個帶有Open方法的字符串。

這意味著不對字符串進行任何處理,您可以filepath.Join直接對原始字符串進行處理:

filePath := filepath.Join(uploadPath, fileName)

注意:您用于http.Dir將參數(shù)轉(zhuǎn)換為的原因http.FileServerDir.Open實現(xiàn)http.Filesystem接口的方法。


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

TA貢獻1876條經(jīng)驗 獲得超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 關(guān)注
  • 354 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號