JavaScript – 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

Wie kann ich einen Button nach dem Laden einer Webseite aktiviert aussehen lassen?

Ich habe mir für mein Intranet ein kleines Video-Portal programmiert - das eigentlich ganz gut funktioniert.
Oben gibt es eine aufklappbare Ansicht mit Haupt und Unterkategorien und wenn eine Unter-Kategorie angeklickt wird öffnet sich die Seite mit einer Übersicht relevanter Videos.

Die Haupt-Kategorie gebe ich als URL-Parameter mit -> das funktioniert auch und es wird verdeckt die zu letzt verwendete Hauptkategorie angewählt.

Was nicht funktioniert, ist den Button für die aktuelle Hauptkategorie im Reitermenü so hervor zu heben als wenn er angeklickt wurde - bzw. den Button zu aktivieren.

JavaScript:

function openCity(evt, cityName) {
  // Declare all variables
  var i, tabcontent, tablinks;


  // Get all elements with class="tabcontent" and hide them
  tabcontent = document.getElementsByClassName("tabcontent");
  for (i = 0; i < tabcontent.length; i++) {
    tabcontent[i].style.display = "none";
  }


  // Get all elements with class="tablinks" and remove the class "active"
  tablinks = document.getElementsByClassName("tablinks");
  for (i = 0; i < tablinks.length; i++) {
    tablinks[i].className = tablinks[i].className.replace(" active", "");
  }

PHP-Script:


$cat = "Musik";
if (isset($_GET['cat']))
{
$cat = ($_GET['cat']);
}

echo '<details><summary> Kategorien: </summary>';
echo '<div class="tab">';

echo '<button type="button" name="Musik" class="tablinks" onclick="openCity(event, \'Musik\')">Musik</button>
<button type="button"  name="Anleitungen" class="tablinks" onclick="openCity(event, \'Anleitungen\')">Anleitungen</button>
<button type="button"  name="Kochen" class="tablinks" onclick="openCity(event, \'Kochen\')">Kochen</button>
<button type="button"  name="Backen" class="tablinks" onclick="openCity(event, \'Backen\')">Backen</button>
<button type="button"  name="Heimwerken" class="tablinks" onclick="openCity(event, \'Heimwerken\')">Heimwerken</button>';
  
echo '</div>';

echo '<!-- Tab content -->
<div id="Musik" class="tabcontent">
<div style="column-count: 5;">
'.$category_Musik.'
</div>
</div>

<div id="Anleitungen" class="tabcontent">
<div style="column-count: 5;">
'.$category_Anleitungen.'
</div>
</div>

<div id="Kochen" class="tabcontent">
<div style="column-count: 5;">
'.$category_Kochen.'
</div>
</div>

<div id="Backen" class="tabcontent">
<div style="column-count: 5;">
'.$category_Backen.'
</div>
</div>

<div id="Heimwerken" class="tabcontent">
<div style="column-count: 5;">
'.$category_Heimwerken.'
</div>
</div>';

echo '</details>';

echo '<SCRIPT type="text/javascript" language="JavaScript">
openCity(event, \''.$cat.'\'); 
</SCRIPT>';

CSS-Definitionen:



/* Style the tab */
.tab {
  overflow: hidden;
  border: 1px solid #ccc;
  background-color: #f1f1f1;
}


/* Style the buttons that are used to open the tab content */
.tab button {
  background-color: inherit;
  float: left;
  border: none;
  outline: none;
  cursor: pointer;
  padding: 14px 16px;
  transition: 0.3s;
}


/* Change background color of buttons on hover */
.tab button:hover {
  background-color: #ddd;
}


/* Create an active/current tablink class */
.tab button.active {
  background-color: #ccc;
}


/* Style the tab content */
.tabcontent {
  display: none;
  padding: 6px 12px;
  border: 1px solid #ccc;
  border-top: none;
}

so sieht es aus:

so soll es nach dem Laden der Seite aussehen:

Hat jemand eine Idee wie ich den Button für die aktuelle Kategorie beim Laden der Seite automatisch aktivieren kann?

Bild zum Beitrag
HTML, Webseite, CSS, JavaScript, HTML5, Code, PHP, Webdesign, Webentwicklung

Meistgelesene Beiträge zum Thema JavaScript