studyPlanImport.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package api
  2. import(
  3. "net/http"
  4. "encoding/json"
  5. "os"
  6. "mime/multipart"
  7. "crypto/rand"
  8. xlsx "../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 := xlsx.ImportXLSX(tempname)
  18. if result == nil{
  19. json.NewEncoder(w).Encode(struct{Error string}{Error: "Error while processing file"})
  20. }
  21. json.NewEncoder(w).Encode(result)
  22. }
  23. func readFile(input multipart.File) string {
  24. var (
  25. size = uint64(0)
  26. buffer = make([]byte, 2 << 20) // 1MiB
  27. )
  28. tempname := GenerateRandomString(16) + ".xlsx"
  29. output, err := os.OpenFile(
  30. tempname,
  31. os.O_WRONLY|os.O_CREATE,
  32. 0666,
  33. )
  34. if err != nil {
  35. printError(err)
  36. return "error"
  37. }
  38. for {
  39. length, err := input.Read(buffer)
  40. if err != nil {
  41. printError(err)
  42. break
  43. }
  44. size += uint64(length)
  45. output.Write(buffer[:length])
  46. }
  47. input.Close()
  48. output.Close()
  49. return tempname
  50. }
  51. func GenerateRandomString(max int) string {
  52. var slice []byte = make([]byte, max)
  53. _, err := rand.Read(slice)
  54. if err != nil {
  55. printError(err)
  56. return ""
  57. }
  58. return string(slice)
  59. }