coollsd commited on
Commit
0e07159
1 Parent(s): e459308

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +45 -23
app.py CHANGED
@@ -2,6 +2,7 @@ from fastapi import FastAPI, File, UploadFile, Request
2
  from fastapi.responses import HTMLResponse, JSONResponse, StreamingResponse
3
  import requests
4
  import time
 
5
  from typing import Dict
6
 
7
  app = FastAPI()
@@ -462,7 +463,7 @@ HTML_CONTENT = """
462
  }
463
  }
464
 
465
- function uploadFile(file) {
466
  progressContainer.innerHTML = '';
467
  progressContainer.style.display = 'block';
468
  loadingSpinner.style.display = 'block';
@@ -476,27 +477,41 @@ HTML_CONTENT = """
476
  const formData = new FormData();
477
  formData.append('file', file);
478
 
479
- const xhr = new XMLHttpRequest();
480
- xhr.open('POST', '/upload', true);
481
- xhr.upload.onprogress = (event) => updateProgress(event, progressBar.querySelector('.progress'));
482
- xhr.onload = function() {
483
- if (xhr.status === 200) {
484
- const response = JSON.parse(xhr.responseText);
485
- if (response.url) {
486
- addResultLink(response.url, file.name);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
487
  } else {
488
- alert('Upload failed: ' + response.error);
489
  }
490
- } else {
491
- alert('Upload failed: ' + xhr.statusText);
492
  }
493
- resetUploadState();
494
- };
495
- xhr.onerror = function() {
496
- alert('Upload failed: Network error');
497
- resetUploadState();
498
- };
499
- xhr.send(formData);
500
  }
501
 
502
  function createProgressBar(fileName) {
@@ -718,10 +733,17 @@ async def upload_file(upload_url: str, file_content: bytes, content_type: str) -
718
 
719
  async def retry_upload(upload_url: str, file_content: bytes, content_type: str, max_retries: int = 5, delay: int = 1) -> bool:
720
  for attempt in range(1, max_retries + 1):
721
- success = await upload_file(upload_url, file_content, content_type)
722
- if success:
723
- return True
 
 
 
 
 
724
  if attempt < max_retries:
725
- time.sleep(delay)
726
  delay *= 2 # Exponential backoff
 
 
727
  return False
 
2
  from fastapi.responses import HTMLResponse, JSONResponse, StreamingResponse
3
  import requests
4
  import time
5
+ import asyncio
6
  from typing import Dict
7
 
8
  app = FastAPI()
 
463
  }
464
  }
465
 
466
+ async function uploadFile(file) {
467
  progressContainer.innerHTML = '';
468
  progressContainer.style.display = 'block';
469
  loadingSpinner.style.display = 'block';
 
477
  const formData = new FormData();
478
  formData.append('file', file);
479
 
480
+ let retryCount = 0;
481
+ const maxRetries = 5;
482
+ const retryDelay = 1000; // 1 second
483
+
484
+ while (retryCount < maxRetries) {
485
+ try {
486
+ const response = await fetch('/upload', {
487
+ method: 'POST',
488
+ body: formData
489
+ });
490
+
491
+ if (!response.ok) {
492
+ throw new Error(`HTTP error! status: ${response.status}`);
493
+ }
494
+
495
+ const result = await response.json();
496
+ if (result.url) {
497
+ addResultLink(result.url, file.name);
498
+ } else {
499
+ alert('Upload failed: ' + result.error);
500
+ }
501
+ break; // Success, exit the loop
502
+ } catch (error) {
503
+ console.error('Upload error:', error);
504
+ retryCount++;
505
+ if (retryCount < maxRetries) {
506
+ alert(`Network error. Retrying in ${retryDelay / 1000} seconds... (Attempt ${retryCount} of ${maxRetries})`);
507
+ await new Promise(resolve => setTimeout(resolve, retryDelay));
508
  } else {
509
+ alert('Upload failed after multiple attempts. Please check your internet connection and try again.');
510
  }
 
 
511
  }
512
+ }
513
+
514
+ resetUploadState();
 
 
 
 
515
  }
516
 
517
  function createProgressBar(fileName) {
 
733
 
734
  async def retry_upload(upload_url: str, file_content: bytes, content_type: str, max_retries: int = 5, delay: int = 1) -> bool:
735
  for attempt in range(1, max_retries + 1):
736
+ try:
737
+ success = await upload_file(upload_url, file_content, content_type)
738
+ if success:
739
+ return True
740
+ print(f"Upload attempt {attempt} failed. Retrying...")
741
+ except Exception as e:
742
+ print(f"Error during upload attempt {attempt}: {e}")
743
+
744
  if attempt < max_retries:
745
+ await asyncio.sleep(delay)
746
  delay *= 2 # Exponential backoff
747
+
748
+ print("Upload failed after all retry attempts")
749
  return False