Webentwicklung – die besten Beiträge

Upload API mit NextJS und Azure Portal funktioniert nicht?

Hallo, ich bekomme wenn ich Videos über die API in Azure Portal hochlade immer eine Fehlermeldung. Manchmale sieht sie so aus:

Parsed files: {
  videoFile: [
    PersistentFile {
      _events: [Object: null prototype],
      _eventsCount: 1,
      _maxListeners: undefined,
      lastModifiedDate: 2024-12-17T10:12:37.964Z,
      filepath: 'C:\\Users\\thoma\\AppData\\Local\\Temp\\19612948a7cd7d81f78632e00.mp4',
      newFilename: '19612948a7cd7d81f78632e00.mp4',
      originalFilename: 'sample-2.mp4',
      mimetype: 'video/mp4',
      hashAlgorithm: false,
      size: 30424618,
      _writeStream: [WriteStream],
      hash: null,
      [Symbol(shapeMode)]: false,
      [Symbol(kCapture)]: false
    }
  ]
}

Manchmal (gefühlt oft bei kleineren Dateien) funktioniert es auch der Log sieht dann so aus:

Uploading file from path: C:\Users\thoma\AppData\Local\Temp\19612948a7cd7d81f78632e00.mp4
Request timed out!
File uploaded to Azure successfully: sample-2.mp4

Hier lade ich noch den API Code hoch:

import { BlobServiceClient, generateBlobSASQueryParameters, BlobSASPermissions } from '@azure/storage-blob';
import formidable from 'formidable';
import fs from 'fs/promises';
import { v4 as uuidv4 } from 'uuid';


export const config = {
  api: {
    bodyParser: false, // Disable default body parsing for file uploads
  },
};


// Azure Storage connection string
const AZURE_STORAGE_CONNECTION_STRING =
  'DefaultEndpointsProtocol=https;AccountName=innowesovideos;AccountKey=uyJz3dlCW/hd+t3Y48pSfuk1Q+pV63S1Hs48uvGIJW3ubaO/ngtSMrzoKRvBE4so7MP9zz73uaLl+AStwmS6EA==;EndpointSuffix=core.windows.net';


export default async function handler(req, res) {
  if (req.method !== 'POST') {
    return res.status(405).json({ message: 'Only POST requests are allowed' });
  }


  let filePath = ''; // Variable to track the file path for cleanup


  try {
    // Set a timeout to prevent stalls
    const timeout = setTimeout(() => {
      console.error('Request timed out!');
      if (!res.writableEnded) {
        res.status(504).json({ message: 'Request timed out. Please try again.' });
      }
    }, 15000); // 15-second timeout


    // Initialize formidable for file parsing
    const form = formidable({
      keepExtensions: true, // Keep file extensions
      maxFileSize: 5000 * 1024 * 1024, 
    });
    console.log('New filesize')


    // Parse the incoming form data
    const { files } = await new Promise((resolve, reject) => {
      form.parse(req, (err, fields, files) => {
        if (err) {
          console.error('Error parsing form:', err);
          reject(err);
        } else {
          resolve({ fields, files });
        }
      });
    });


    console.log('Parsed files:', files);


    // Normalize videoFile input (handle single and multiple files)
    const fileData = Array.isArray(files.videoFile) ? files.videoFile[0] : files.videoFile;


    // Validate file presence and format
    if (!fileData || !fileData.filepath) {
      throw new Error('No video file provided.');
    }


    filePath = fileData.filepath;
    if (!filePath) throw new Error('No valid file path found.');
    if (fileData.mimetype !== 'video/mp4') throw new Error('Only MP4 files are allowed.');


    console.log('Uploading file from path:', filePath);


    // Generate a unique file name for Azure Blob Storage
    const fileName = fileData.originalFilename || `${uuidv4()}.mp4`;


    // Load the file as a buffer
    const fileBuffer = await fs.readFile(filePath);


    // Initialize Azure Blob Storage Client
    const blobServiceClient = BlobServiceClient.fromConnectionString(AZURE_STORAGE_CONNECTION_STRING);
    const containerClient = blobServiceClient.getContainerClient('videos');
    const blockBlobClient = containerClient.getBlockBlobClient(fileName);


    // Upload the file to Azure Blob Storage
    await blockBlobClient.uploadData(fileBuffer, {
      blobHTTPHeaders: { blobContentType: 'video/mp4' },
    });
    // Generate a SAS token for the uploaded file
    const sasToken = generateBlobSASQueryParameters(
      {
        containerName: 'videos',
        blobName: fileName,
        permissions: BlobSASPermissions.parse('r'), // Read permissions
        startsOn: new Date(),
        expiresOn: new Date(new Date().valueOf() + 3600 * 1000), // Token valid for 1 hour
      },
      blobServiceClient.credential
    ).toString();
    const videoUrl = `${blockBlobClient.url}?${sasToken}`;
   
    clearTimeout(timeout);

    return res.status(200).json({ message: 'Video uploaded successfully', videoUrl });
  } catch (error) {
    console.error('Error during upload:', error.message);
    return res.status(500).json({ message: 'File upload failed', error: error.message });
  } finally {
    
    if (filePath) {
      try {
        await fs.unlink(filePath);
        console.log(`Temporary file deleted: ${filePath}`);
      } catch (cleanupErr) {
        console.error(`Failed to delete temporary file: ${filePath}`, cleanupErr);
      }
    }
  }
} 

Danke!

HTML, JavaScript, Programmiersprache, Webentwicklung, azure, React

Paypal SDK von USD auf EUR umstellen funktioniert nicht?

Ich habe beide Stellen im Code geändert:

script.src = `https://www.paypal.com/sdk/js?client-id=${clientId}&currency=EUR`;

und

currency_code: 'EUR',

Bekomme jedoch den folgenden Fehler https://pastebin.com/6eNUSdX9

Wichtigster Ausschnitt:

Error: Unexpected currency: EUR passed to order.create. Please ensure you are passing /sdk/js?currency=EUR in the paypal script tag. 

Der Fehler tritt auf, wenn ich USD auf EUR ändere. Hier ist meine

/app/paypal/page.tsx

https://pastebin.com/9GM500eR die ganze datei

Wichtigster Ausschnitt: der mit USD funktioniert:

<PayPalScriptProvider options={{ clientId }}>
            <div className="flex justify-center">
              <PayPalButtons
                style={{
                  layout: 'vertical',
                  color: 'blue',
                  shape: 'rect',
                  label: 'paypal',
                }}
                createOrder={(data, actions) => {
                  if (!actions || !actions.order) {
                    console.error('Fehler: actions.order ist nicht definiert');
                    return Promise.reject('Fehler bei der Erstellung der Bestellung');
                  }
 
                  return actions.order.create({
                    purchase_units: [
                      {
                        amount: {
                          currency_code: 'USD',
                          value: '100.00',
                        },
                      },
                    ],
                    intent: 'CAPTURE'
                  });
                }}
                onApprove={(data, actions) => {
                  if (!actions || !actions.order) {
                    console.error('Fehler: actions.order ist nicht definiert');
                    return Promise.reject('Fehler bei der Genehmigung der Bestellung');
                  }
 
                  return actions.order.capture().then((details) => {
                    console.log('Zahlung erfolgreich abgeschlossen:', details);
                    setPaymentSuccess(true);  // Zeigt die Erfolgsmeldung an
                    setErrorMessage('');  // Setzt die Fehlermeldung zurück
                    return Promise.resolve();
                  });
                }}
                onError={(err) => {
                  console.error('Fehler bei der PayPal-Zahlung:', err);
                  setErrorMessage('Es gab ein Problem bei Ihrer Zahlung. Bitte versuchen Sie es erneut.'); // Zeigt die Fehlermeldung an
                  setPaymentSuccess(false); // Setzt den Zahlungserfolgsstatus zurück
                }}
              />
            </div>
          </PayPalScriptProvider>

Meine

env Datei ist folgendermaßen konfiguriert:
makefile
Code kopieren
NEXT_PUBLIC_PAYPAL_CLIENT_ID = "12345"
PAYPAL_CLIENT_ID = "12345"
PAYPAL_CLIENT_SECRET = "ABCDEF"
PAYPAL_WEBHOOK_SECRET="XYZ123"

Ich habe den currency_code von 'USD' auf 'EUR' geändert und auch die URL des PayPal-Skripts angepasst:

script.src = `https://www.paypal.com/sdk/js?client-id=${clientId}&currency=EUR`;

Trotzdem bekomme ich den Fehler, dass EUR nicht als Währung erkannt wird.

Ich habe die Dokumentation auf PayPal Developer überprüft, und laut dieser ist

EUR

der richtige Währungscode.

  • Ich benutze Next.js 15 und habe auf React 18 downgraden müssen, da React 19 nicht mit
@paypal/react-paypal-js
  • kompatibel ist aber spielt eigentlich keiner olle und sowohl im sandbox oder live modus dasselbe das man nach dem klick auf dem button mit EUR einen fehler bekommt.

Kann mir jemand helfen, was hier das Problem ist?

PC, Computer, Internet, App, Technik, IT, Webseite, JavaScript, Code, Informatik, PayPal, Programmiersprache, sdk, Webentwicklung, node.js

Meistgelesene Beiträge zum Thema Webentwicklung