admin管理员组

文章数量:1336281

Cannot for the life of me figure out why the blob isn't uploading. I'm getting everything except the file. The file just isn't appended.

i can get it in if i base64 encode the blob, but then its causing problems loading it as a file.

for reference: apiClient is just a custom wrapper around fetch.

Client Side:

export async function uploadToServer(apiClient: AGFarmsClient, uri: string, filePath: string, bucket: string, mimeType: string) {
  console.log("Starting file upload...");
  console.log("URI: ", uri);

  // Fetch the file from the provided URI
  const r = await fetch(uri);
  const file = await r.blob();

  try {

    const formData = new FormData();
    formData.append('file_name', filePath);
    formData.append('bucket', bucket);
    formData.append('mime_type', mimeType);
    formData.append('file', file);

    // Step 4: Make the POST request to upload the file
    const uploadResponse = await apiClient.post("/resources/media", formData, true);
    console.log("Upload response:", uploadResponse);

    return uploadResponse;

  } catch (error) {
    console.error("Error during file upload: ", error);
    throw error;
  }
}
async post<T>(url: string, data?: any, isFormData: boolean = false, customHeaders?: Record<string, string>): Promise<AGFarmsResponse<T>> {
    if (isFormData) {
      this.headers.delete('Content-Type'); // Remove any Content-Type set
    } else {
      this.headers.set('Content-Type', 'application/json');
    }

    const body = isFormData ? data : JSON.stringify(data);
    return this.request<T>(url, 'POST', body, customHeaders);
  }
private async request<T>(
    url: string,
    method: string,
    body?: any,
    customHeaders?: Record<string, string>
  ): Promise<AGFarmsResponse<T>> {
    const requestUrl = new URL(url, this.baseURL);
    const requestOptions: RequestInit = {
      method,
      headers: new Headers(this.headers), // Start with the default headers
    };

    // Add custom headers if provided
    if (customHeaders) {
      const headers = new Headers(requestOptions.headers);
      Object.entries(customHeaders).forEach(([key, value]) => {
        headers.set(key, value);
      });
      requestOptions.headers = headers;
    }

    try {
      const response = await fetch(requestUrl.toString(), requestOptions);
      const responseData = await response.json();

      return this.normalizeResponse<T>(response, responseData);
    } catch (error) {
      return this.normalizeError(error as Error, url, method);
    }
  }

本文标签: typescriptupload function not working on reactnative expoStack Overflow