@Summary Upload file @Description Swagger notice: Swagger 2.0 doesn't support file upload with a `content-type` different than `application/x-www-form-urlencoded`. @ID upload-file @Security CoderSessionToken @Produce json @Accept application/x-tar @Tags Files @Param Content-Type header string true "
(rw http.ResponseWriter, r *http.Request)
| 45 | // @Success 201 {object} codersdk.UploadResponse "Returns newly created file" |
| 46 | // @Router /api/v2/files [post] |
| 47 | func (api *API) postFile(rw http.ResponseWriter, r *http.Request) { |
| 48 | ctx := r.Context() |
| 49 | apiKey := httpmw.APIKey(r) |
| 50 | |
| 51 | contentType := r.Header.Get("Content-Type") |
| 52 | switch contentType { |
| 53 | case tarMimeType, zipMimeType, windowsZipMimeType: |
| 54 | default: |
| 55 | httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{ |
| 56 | Message: fmt.Sprintf("Unsupported content type header %q.", contentType), |
| 57 | }) |
| 58 | return |
| 59 | } |
| 60 | |
| 61 | r.Body = http.MaxBytesReader(rw, r.Body, HTTPFileMaxBytes) |
| 62 | data, err := io.ReadAll(r.Body) |
| 63 | if err != nil { |
| 64 | httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{ |
| 65 | Message: "Failed to read file from request.", |
| 66 | Detail: err.Error(), |
| 67 | }) |
| 68 | return |
| 69 | } |
| 70 | |
| 71 | if contentType == zipMimeType || contentType == windowsZipMimeType { |
| 72 | zipReader, err := zip.NewReader(bytes.NewReader(data), int64(len(data))) |
| 73 | if err != nil { |
| 74 | httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{ |
| 75 | Message: "Incomplete .zip archive file.", |
| 76 | Detail: err.Error(), |
| 77 | }) |
| 78 | return |
| 79 | } |
| 80 | |
| 81 | data, err = archive.CreateTarFromZip(zipReader, HTTPFileMaxBytes) |
| 82 | if err != nil { |
| 83 | switch { |
| 84 | case errors.Is(err, archive.ErrArchiveTooLarge): |
| 85 | httpapi.Write(ctx, rw, http.StatusRequestEntityTooLarge, codersdk.Response{ |
| 86 | Message: "Expanded .zip archive exceeds maximum size.", |
| 87 | }) |
| 88 | return |
| 89 | case errors.Is(err, archive.ErrInvalidZipContent): |
| 90 | httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{ |
| 91 | Message: "Invalid .zip archive contents.", |
| 92 | }) |
| 93 | return |
| 94 | default: |
| 95 | httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{ |
| 96 | Message: "Internal error processing .zip archive.", |
| 97 | Detail: err.Error(), |
| 98 | }) |
| 99 | return |
| 100 | } |
| 101 | } |
| 102 | contentType = tarMimeType |
| 103 | } |
| 104 |
nothing calls this directly
no test coverage detected