fileUpload.go 1.4 KB

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