fileUpload.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package bullet
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "io"
  6. "mime/multipart"
  7. "net/http"
  8. "os"
  9. )
  10. type fileUpload struct {
  11. FileName string `json:"file_name"`
  12. FileType string `json:"file_type"`
  13. Type string `json:"type"`
  14. Title string `json:"title"`
  15. Body string `json:"body"`
  16. FileUrl string `json:"file_url"`
  17. UploadUrl string `json:"upload_url"`
  18. }
  19. func newFileUpload(filename, fileType string) fileUpload {
  20. f := fileUpload{Type: "file", FileName: filename, FileType: fileType}
  21. return f
  22. }
  23. func (f fileUpload) getReader() (*bytes.Buffer, error) {
  24. jsonBytes, err := json.Marshal(f)
  25. if err != nil {
  26. return nil, err
  27. }
  28. buffer := bytes.NewBuffer(jsonBytes)
  29. return buffer, err
  30. }
  31. func getFileRequest(filePath string, upload fileUpload) (*http.Request, error) {
  32. buffer := &bytes.Buffer{}
  33. multipartWriter := multipart.NewWriter(buffer)
  34. file, errOpen := os.Open(filePath)
  35. if errOpen != nil {
  36. return nil, errOpen
  37. }
  38. defer file.Close()
  39. writer, errWriter := multipartWriter.CreateFormFile("file", upload.FileName)
  40. if errWriter != nil {
  41. return nil, errWriter
  42. }
  43. _, errCopy := io.Copy(writer, file)
  44. if errCopy != nil {
  45. return nil, errCopy
  46. }
  47. errMultipartClose := multipartWriter.Close()
  48. if errMultipartClose != nil {
  49. return nil, errMultipartClose
  50. }
  51. request, errRequest := http.NewRequest(http.MethodPost, upload.UploadUrl, buffer)
  52. if errRequest != nil {
  53. return nil, errRequest
  54. }
  55. request.Header.Add("Content-Type", multipartWriter.FormDataContentType())
  56. return request, nil
  57. }