typescript - upload function not working on react-native expo - Stack Overflow

Cannot for the life of me figure out why the blob isn't uploading. I'm getting everything exc

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);
    }
  }

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742405530a4437768.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信