fileUpload.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. }
  18. func newFileUpload(filename, fileType string) fileUpload {
  19. f := fileUpload{Type: "file", FileName: filename, FileType: fileType}
  20. return f
  21. }
  22. func (f fileUpload) getReader() (*bytes.Buffer, error) {
  23. return getReader(f)
  24. }
  25. func getFileRequest(filePath string, upload fileUpload) (*http.Request, error) {
  26. buffer := &bytes.Buffer{}
  27. multipartWriter := multipart.NewWriter(buffer)
  28. file, errOpen := os.Open(filePath)
  29. if errOpen != nil {
  30. return nil, errOpen
  31. }
  32. defer file.Close()
  33. writer, errWriter := multipartWriter.CreateFormFile("file", upload.FileName)
  34. if errWriter != nil {
  35. return nil, errWriter
  36. }
  37. _, errCopy := io.Copy(writer, file)
  38. if errCopy != nil {
  39. return nil, errCopy
  40. }
  41. errMultipartClose := multipartWriter.Close()
  42. if errMultipartClose != nil {
  43. return nil, errMultipartClose
  44. }
  45. request, errRequest := http.NewRequest(http.MethodPost, upload.UploadUrl, buffer)
  46. if errRequest != nil {
  47. return nil, errRequest
  48. }
  49. request.Header.Add("Content-Type", multipartWriter.FormDataContentType())
  50. return request, nil
  51. }