upload.go 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  1. package upload
  2. import (
  3. "errors"
  4. "io"
  5. "log"
  6. "net/http"
  7. "os"
  8. "path/filepath"
  9. user "imuslab.com/arozos/mod/user"
  10. )
  11. type chunk struct {
  12. PartFilename string
  13. DestFilename string
  14. }
  15. func StreamUploadToDisk(userinfo *user.User, w http.ResponseWriter, r *http.Request) ([]string, error) {
  16. //Check if this userinfo is valid
  17. if userinfo == nil {
  18. return []string{}, errors.New("Invalid userinfo")
  19. }
  20. vpath, ok := r.URL.Query()["path"]
  21. if !ok || len(vpath) == 0 {
  22. return []string{}, errors.New("Invalid upload destination")
  23. }
  24. //Get the upload destination realpath
  25. realUploadPath, err := userinfo.VirtualPathToRealPath(vpath[0])
  26. if err != nil {
  27. //Return virtual path to real path translation error
  28. return []string{}, err
  29. }
  30. //Try to parse the FORM POST using multipart reader
  31. reader, err := r.MultipartReader()
  32. if err != nil {
  33. log.Println("Upload failed: " + err.Error())
  34. return []string{}, err
  35. }
  36. //Start write process
  37. uplaodedFiles := map[string]string{}
  38. for {
  39. part, err := reader.NextPart()
  40. if err == io.EOF {
  41. break
  42. } else if err != nil {
  43. //Connection lost when uploading. Remove the uploading file.
  44. clearFailedUploadChunks(uplaodedFiles)
  45. return []string{}, errors.New("Upload failed")
  46. }
  47. defer part.Close()
  48. //Check if this is file or other paramters
  49. if part.FileName() != "" {
  50. //This part is a part of a file. Write it to destination folder
  51. tmpFilepath := filepath.Join(realUploadPath, part.FileName()+".tmp")
  52. //Check if this part is uploaded before. If not but the .tmp file exists
  53. //This is from previous unsuccessful upload and it should be reoved
  54. _, ok := uplaodedFiles[part.FileName()]
  55. if !ok && fileExists(tmpFilepath) {
  56. //This chunk is first chunk of the file and the .tmp file already exists.
  57. //Remove it
  58. log.Println("Removing previous failed upload: ", tmpFilepath)
  59. os.Remove(tmpFilepath)
  60. }
  61. //Check if the uploading target folder exists. If not, create it
  62. if !fileExists(filepath.Dir(tmpFilepath)) {
  63. os.MkdirAll(filepath.Dir(tmpFilepath), 0755)
  64. }
  65. //Open the file and write to it using append mode
  66. d, err := os.OpenFile(tmpFilepath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0775)
  67. if err != nil {
  68. //Failed to create new file.
  69. clearFailedUploadChunks(uplaodedFiles)
  70. return []string{}, errors.New("Write to disk failed")
  71. }
  72. io.Copy(d, part)
  73. d.Close()
  74. //Record this file
  75. uplaodedFiles[part.FileName()] = tmpFilepath
  76. } else {
  77. //Unknown stuffs
  78. continue
  79. }
  80. }
  81. //Remove the .tmp extension for the file.
  82. uploadedFilepaths := []string{}
  83. for thisFilename, thisFilepath := range uplaodedFiles {
  84. thisFilename = filepath.Base(thisFilename)
  85. finalDestFilename := filepath.Join(filepath.Dir(thisFilepath), thisFilename)
  86. //Remove the .tmp from the upload by renaming it as the original name
  87. err = os.Rename(thisFilepath, finalDestFilename)
  88. if err != nil {
  89. clearFailedUploadChunks(uplaodedFiles)
  90. return []string{}, err
  91. }
  92. uploadedFilepaths = append(uploadedFilepaths, finalDestFilename)
  93. log.Println(userinfo.Username+" uploaded: ", filepath.Base(thisFilepath))
  94. }
  95. return uploadedFilepaths, nil
  96. }
  97. //This function remove all the chunks for failed file upload from disk
  98. func clearFailedUploadChunks(uplaodedFiles map[string]string) {
  99. for _, tmpFiles := range uplaodedFiles {
  100. os.Remove(tmpFiles)
  101. }
  102. }