studyPlanImport.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package api
  2. import(
  3. "net/http"
  4. "encoding/json"
  5. "os"
  6. "mime/multipart"
  7. "crypto/rand"
  8. xls "../schedule"
  9. )
  10. func ImportPlanRoute(w http.ResponseWriter, r *http.Request){
  11. input, _, err := r.FormFile("uploadfile")
  12. if err != nil {
  13. json.NewEncoder(w).Encode(struct{Error string}{Error: "Error read upload file"})
  14. return
  15. }
  16. tempname := readFile(input)
  17. result := xls.ImportXLSX(tempname)
  18. json.NewEncoder(w).Encode(result)
  19. }
  20. func readFile(input multipart.File) string {
  21. var (
  22. size = uint64(0)
  23. buffer = make([]byte, 2 << 20) // 1MiB
  24. )
  25. tempname := GenerateRandomString(16) + ".xlsx"
  26. output, err := os.OpenFile(
  27. tempname,
  28. os.O_WRONLY|os.O_CREATE,
  29. 0666,
  30. )
  31. if err != nil {
  32. printError(err)
  33. return "error"
  34. }
  35. for {
  36. length, err := input.Read(buffer)
  37. if err != nil {
  38. printError(err)
  39. break
  40. }
  41. size += uint64(length)
  42. output.Write(buffer[:length])
  43. }
  44. input.Close()
  45. output.Close()
  46. return tempname
  47. }
  48. func GenerateRandomString(max int) string {
  49. var slice []byte = make([]byte, max)
  50. _, err := rand.Read(slice)
  51. if err != nil {
  52. printError(err)
  53. return ""
  54. }
  55. return string(slice)
  56. }