我的文件系统的目录如下。
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
跃然一笑
幕布斯6054654
相关分类