SWFUpload +"upload.php"

thetetsuo

Mitglied
Hallo,

leider verzweifle ich langsam an der simplen(sic) Aufgabe ein Formular mit Upload-Möglichkeit zu erstellen. Habe inzwischen sämtliche Tutorials, Codeschnippsel und Out-of-the-box Möglichkeiten durch,und komme nicht weiter.

Nachdem ich nun SWFUpload entdeckt habe, und mir die Demo sehr gut gefällt, wollte ich das Beispiel meinen Wünschen gemäß anpassen.
Hier die Demo:
http://demo.swfupload.org/formsdemo/

Was in dieser Demo fehlt ist die "upload.php" im Hintergrund, welche die Formulardaten verarbeitet. Im Forum von SWFUpload wurde sogar von Entwickler eine Master "upload.php" gepostet. Aber aus dieser werde ich absolut nicht schlau
Siehe hier: upload.php

Könnte mir bitte jemand helfen, der SWFUpload benutzt oder sich mit dieser PHP Datei auskennt ?

Gibt es denn kein Formular (mit Upload) das schick UND einfach ist :confused:
 
Also ein Dateiupload ist eine von den Anwendungen die man als erstes lernt und die upload php ist doch echt übersichtlich und gut dokumentiert. Wenn du natürlich absolut keine Ahnung von PHP hast solltest du das lieber lassen oder jemanden damit beauftragen.
Nichts desto trotz:
PHP:
$save_path = getcwd() . "/uploads/";				// The path were we will save the file (getcwd() may not be reliable and should be tested in your environment)
$upload_name = "Filedata";
$max_file_size_in_bytes = 2147483647;				// 2GB in bytes
$extension_whitelist = array("jpg", "gif", "png");	// Allowed file extensions
$valid_chars_regex = '.A-Z0-9_ !@#$%^&()+={}\[\]\',~`-';				// Characters allowed in the file name (in a Regular Expression format)

Bei den Settings gibts du einfach deine Daten an.

$save_path ist der Pfad wohin die Datei auf dem Server gespeichert werden soll.
$upload_name ist der Name des Felds in deinem Formular welches die Datei hochlädt

und bei $valid_chars_regex fügst du einfach swf mit ein oder ersetzt alles durch swf

é voilà... Die Datei wird in dem Angegebenen Verzeichnis gespeichert.
 
@hasta_jesaja

Eine Upload Funktion mit PHP zu realisieren ist ja auch nicht unbedingt das Problem!

Ich glaube Du hast a) meinen Beitragstitel missverstanden und b) dir das von mir verlinkte Skript nicht angesehen. SWFUpload ist "JavaScript/Flash library to get the best of both worlds" (Zitat SWFUpload.org)

Zu a) Ich will keine swf Datei uploaden !

Zu b) Ich finde die verlinkte "upload.php" sehr wohl kompliziert.

Falls Du Dir das Ganze nochmal ansehen willst, dann verstehst Du was ich meine.
Nichtsdestotrotz vielen Dank für Deine Hilfe !
 
Also die upload.php hab ich mir angesehen und ich muss sagen das das sehr einfach gestrickt ist, ich hab definitiv viel schlimmeres gesehen. Und warum sagst du das ne "upload Funktion" nicht das Problem ist?

Worum geht es denn hier?

leider verzweifle ich langsam an der simplen(sic) Aufgabe ein Formular mit Upload-Möglichkeit zu erstellen.

Also willst du doch eine Datei hochladen, egal ob jetzt swf oder nicht.
Was du dazu in der upload PHP ändern musst, hab ich ja schon gesagt.
Wie man ein HTML Formular anpasst ist natürlich vorraussetzung UND das man das Formular natürlich dann an die upload.php schickt, fertig.

So sollte das gehen.
 
Okay...dann mal anders:

Demo ansehen hier (Bitte mal testweise etwas hochladen):
Upload-Formular

Hier das Fformular:
PHP:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>SWFUpload v2.0 Classic Form Demo</title>

	<link href="../css/default.css" rel="stylesheet" type="text/css" />
	<script type="text/javascript" src="../swfupload/swfupload.js"></script>
	<script type="text/javascript" src="js/swfupload.graceful_degradation.js"></script>
	<script type="text/javascript" src="js/handlers.js"></script>
	<script type="text/javascript">
		var swf_upload_control;

        window.onload = function () {
            swf_upload_control = new SWFUpload({
				// Backend settings
				upload_url: "../formsdemo/upload.php",	// Relative to the SWF file, you can use an absolute URL as well.
				file_post_name: "resume_file",

				// Flash file settings
				file_size_limit : "10240",	// 10 MB
				file_types : "*.*",	// or you could use something like: "*.doc;*.wpd;*.pdf",
				file_types_description : "All Files",
				file_upload_limit : "0", // Even though I only want one file I want the user to be able to try again if an upload fails
				file_queue_limit : "1", // this isn't needed because the upload_limit will automatically place a queue limit

				// Event handler settings
				swfupload_loaded_handler : myShowUI,
				
				//file_dialog_start_handler : fileDialogStart,		// I don't need to override this handler
				file_queued_handler : fileQueued,
				file_queue_error_handler : fileQueueError,
				file_dialog_complete_handler : fileDialogComplete,
				
				//upload_start_handler : uploadStart,	// I could do some client/JavaScript validation here, but I don't need to.
				upload_progress_handler : uploadProgress,
				upload_error_handler : uploadError,
				upload_success_handler : uploadSuccess,
				upload_complete_handler : uploadComplete,

				// Flash Settings
				flash_url : "../swfupload/swfupload_f9.swf",	// Relative to this file

				// UI settings
				swfupload_element_id : "flashUI",		// setting for the graceful degradation plugin
				degraded_element_id : "degradedUI",

				custom_settings : {
					progress_target : "fsUploadProgress",
					upload_successful : false
				},
				
				// Debug settings
				debug: false
			});

        }

        function myShowUI() {
            var btnSubmit = document.getElementById("btnSubmit");
			var txtLastName = document.getElementById("lastname");
			var txtFirstName = document.getElementById("firstname");
			var txtEducation = document.getElementById("education");
			var txtReferences = document.getElementById("references");
			
			btnSubmit.onclick = doSubmit;
			btnSubmit.disabled = true;
			
			txtLastName.onchange = validateForm;
			txtFirstName.onchange = validateForm;
			txtEducation.onchange = validateForm;
			txtReferences.onchange = validateForm;
			
			
            SWFUpload.swfUploadLoaded.apply(this);  // Let SWFUpload finish loading the UI.
			validateForm();
        }
		
		function validateForm() {
			var txtLastName = document.getElementById("lastname");
			var txtFirstName = document.getElementById("firstname");
			var txtEducation = document.getElementById("education");
			var txtFileName = document.getElementById("txtFileName");
			var txtReferences = document.getElementById("references");
			
			var is_valid = true;
			if (txtLastName.value === "") is_valid = false;
			if (txtFirstName.value === "") is_valid = false;
			if (txtEducation.value === "") is_valid = false;
			if (txtFileName.value === "") is_valid = false;
			if (txtReferences.value === "") is_valid = false;
			
			document.getElementById("btnSubmit").disabled = !is_valid;
		
		}
		
		function fileBrowse() {
			var txtFileName = document.getElementById("txtFileName");
			txtFileName.value = "";

			this.cancelUpload();
			this.selectFile();
		}
		
		
        // Called by the submit button to start the upload
		function doSubmit(e) {
			e = e || window.event;
			if (e.stopPropagation) e.stopPropagation();
			e.cancelBubble = true;
			
			try {
				swf_upload_control.startUpload();
			} catch (ex) {

            }
            return false;
	    }

		 // Called by the queue complete handler to submit the form
	    function uploadDone() {
			try {
				document.forms[0].submit();
			} catch (ex) {
				alert("Error submitting form");
			}
	    }
	</script>

</head>
<body>
	<div class="title"><a class="likeParent" href="../index.php">SWFUpload v2.0 Classic Form Demo</a></div>

	<form id="form1" action="thanks.php" enctype="multipart/form-data" method="post">
		<div class="content">
			<div>This demo shows how SWFUpload might be combined with an HTML form.  It also demonstrates graceful degradation (using the graceful degradation plugin).
			This demo also demonstrates the use of the server_data parameter.  This demo requires Flash Player 9+</div>
			<fieldset >
				<legend>Submit your Application</legend>
				<table style="vertical-align:top;">
					<tr>
						<td>
							Last Name:
						</td>
						<td>
							<input name="lastname" id="lastname" type="text" style="width: 200px" />
						</td>
					</tr>
					<tr>
						<td>
							First Name:
						</td>
						<td>
							<input name="firstname" id="firstname" type="text" style="width: 200px" />
						</td>
					</tr>
					<tr>
						<td>
							Education:
						</td>
						<td>
							<textarea name="education"  id="education" cols="0" rows="0" style="width: 400px; height: 100px;"></textarea>
						</td>
					</tr>
					<tr>
						<td>
							Resume:
						</td>
						<td>

							<div id="flashUI" style="display: none;">
								<!-- The UI only gets displayed if SWFUpload loads properly -->
								<div>
									<input type="text" id="txtFileName" disabled="true" style="border: solid 1px; background-color: #FFFFFF;" /><input id="btnBrowse" type="button" value="Browse..." onclick="fileBrowse.apply(swf_upload_control)" /> (10 MB max)
								</div>
								<div class="flash" id="fsUploadProgress">
									<!-- This is where the file progress gets shown.  SWFUpload doesn't update the UI directly.
										The Handlers (in handlers.js) process the upload events and make the UI updates -->
								</div>
								<input type="hidden" name="hidFileID" id="hidFileID" value="" /><!-- This is where the file ID is stored after SWFUpload uploads the file and gets the ID back from upload.php -->
							</div>
							<div id="degradedUI">
								<!-- This is the standard UI.  This UI is shown by default but when SWFUpload loads it will be
								hidden and the "flashUI" will be shown -->
								<input type="file" name="resume_degraded" id="resume_degraded" /> (10 MB max)<br/>
							</div>
						</td>
					</tr>
					<tr>
						<td>
							References:
						</td>
						<td>
							<textarea name="references" id="references" cols="0" rows="0" style="width: 400px; height: 100px;"></textarea>
						</td>
					</tr>
				</table>
				<br />
				<input type="submit" value="Submit Application" id="btnSubmit" />
			</fieldset>
		</div>
	</form>
</body>
</html>

Und hier die "upload.php" auf die das Formular verweist:
PHP:
<?php


// Code for Session Cookie workaround
	if (isset($_POST["PHPSESSID"])) {
		session_id($_POST["PHPSESSID"]);
	} else if (isset($_GET["PHPSESSID"])) {
		session_id($_GET["PHPSESSID"]);
	}

	session_start();

// Check post_max_size (http://us3.php.net/manual/en/features.file-upload.php#73762)
	$POST_MAX_SIZE = ini_get('post_max_size');
	$unit = strtoupper(substr($POST_MAX_SIZE, -1));
	$multiplier = ($unit == 'M' ? 1048576 : ($unit == 'K' ? 1024 : ($unit == 'G' ? 1073741824 : 1)));

	if ((int)$_SERVER['CONTENT_LENGTH'] > $multiplier*(int)$POST_MAX_SIZE && $POST_MAX_SIZE) {
		header("HTTP/1.1 500 Internal Server Error");
		echo "POST exceeded maximum allowed size.";
		exit(0);
	}

// Settings
	$save_path = getcwd() . "/uploads/";				// The path were we will save the file (getcwd() may not be reliable and should be tested in your environment)
	$upload_name = "Filedata";
	$max_file_size_in_bytes = 2147483647;				// 2GB in bytes
	$extension_whitelist = array("jpg", "gif", "png");	// Allowed file extensions
	$valid_chars_regex = '.A-Z0-9_ !@#$%^&()+={}\[\]\',~`-';				// Characters allowed in the file name (in a Regular Expression format)
	
// Other variables	
	$MAX_FILENAME_LENGTH = 260;
	$file_name = "";
	$file_extension = "";
	$uploadErrors = array(
        0=>"There is no error, the file uploaded with success",
        1=>"The uploaded file exceeds the upload_max_filesize directive in php.ini",
        2=>"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form",
        3=>"The uploaded file was only partially uploaded",
        4=>"No file was uploaded",
        6=>"Missing a temporary folder"
	);


// Validate the upload
	if (!isset($_FILES[$upload_name])) {
		HandleError("No upload found in \$_FILES for " . $upload_name);
		exit(0);
	} else if (isset($_FILES[$upload_name]["error"]) && $_FILES[$upload_name]["error"] != 0) {
		HandleError($uploadErrors[$_FILES[$upload_name]["error"]]);
		exit(0);
	} else if (!isset($_FILES[$upload_name]["tmp_name"]) || !@is_uploaded_file($_FILES[$upload_name]["tmp_name"])) {
		HandleError("Upload failed is_uploaded_file test.");
		exit(0);
	} else if (!isset($_FILES[$upload_name]['name'])) {
		HandleError("File has no name.");
		exit(0);
	}
	
// Validate the file size (Warning the largest files supported by this code is 2GB)
	$file_size = @filesize($_FILES[$upload_name]["tmp_name"]);
	if (!$file_size || $file_size > $max_file_size_in_bytes) {
		HandleError("File exceeds the maximum allowed size");
		exit(0);
	}


// Validate file name (for our purposes we'll just remove invalid characters)
	$file_name = preg_replace('/[^'.$valid_chars_regex.']|\.+$/i', "", basename($_FILES[$upload_name]['name']));
	if (strlen($file_name) == 0 || strlen($file_name) > $MAX_FILENAME_LENGTH) {
		HandleError("Invalid file name");
		exit(0);
	}


// Validate that we won't over-write an existing file
	if (file_exists($save_path . $file_name)) {
		HandleError("File with this name already exists");
		exit(0);
	}

// Validate file extention
	$path_info = pathinfo($_FILES[$upload_name]['name']);
	$file_extension = $path_info["extension"];
	$is_valid_extension = false;
	foreach ($extension_whitelist as $extension) {
		if ($file_extension == $extension) {
			$is_valid_extension = true;
			break;
		}
	}
	if (!$is_valid_extension) {
		HandleError("Invalid file extension");
		exit(0);
	}

// Validate file contents (extension and mime-type can't be trusted)
	/*
		Validating the file contents is OS and web server configuration dependant.  Also, it may not be reliable.
		See the comments on this page: http://us2.php.net/fileinfo
		
		Also see http://72.14.253.104/search?q=cache:3YGZfcnKDrYJ:www.scanit.be/uploads/php-file-upload.pdf+php+file+command&hl=en&ct=clnk&cd=8&gl=us&client=firefox-a
		 which describes how a PHP script can be embedded within a GIF image file.
		
		Therefore, no sample code will be provided here.  Research the issue, decide how much security is
		 needed, and implement a solution that meets the needs.
	*/


// Process the file
	/*
		At this point we are ready to process the valid file. This sample code shows how to save the file. Other tasks
		 could be done such as creating an entry in a database or generating a thumbnail.
		 
		Depending on your server OS and needs you may need to set the Security Permissions on the file after it has
		been saved.
	*/
	if (!@move_uploaded_file($_FILES[$upload_name]["tmp_name"], $save_path.$file_name)) {
		HandleError("File could not be saved: ". $save_path.$file_name);
		exit(0);
	}

// Return output to the browser (only supported by SWFUpload for Flash Player 9)

	echo "File Received ". $save_path.$file_name;
	exit(0);


/* Handles the error output.  This function was written for SWFUpload for Flash Player 8 which
cannot return data to the server, so it just returns a 500 error. For Flash Player 9 you will
want to change this to return the server data you want to indicate an error and then use SWFUpload's
uploadSuccess to check the server_data for your error indicator. */
function HandleError($message) {
	header("HTTP/1.1 500 Internal Server Error");
	echo $message;
}
?>

Der Name des Input Feldes im Formular ist "resume_degraded". In der Upload wird $upload_name = "Filedata"; angegeben. Das soll gleich sein? Funtioniert aber leider nicht!

Ich glaube ich muss mich hier zuerst einmal in die Funktionsweise von SWFUpload einarbeiten. Laut des Forums soll aber eine "einfache" Upload.php genügen. Quasi ein simples Verarbeiten der Formulardaten plus move_uploaded_file ...
 
Ja, muss gleich sein und wenn $save_path jetzt noch ein ordner mit entsprechenden schreibrechten auf dem Server ist und die Datei die du testweise hochlädst eine erlaubte Endung wie in $valid_chars_regex angegeben hat müsste das funktionieren.

Gibt es Fehlerausgaben? Kommt das file am Server an? Oder klappt nur das move_file() nicht?
 
Der Thread is zwar jetzt schon etwas älter, und du hast das Problem mit Sicherheit gelöst. Aber vielleicht stoßen ja noch mehr Leute auf das gleiche Problem, daher will ich hier mal ne lösung Posten. Ich hatte nämlich vor kurzem das selbe Problem, und hab ziemlich lange gebraucht um das zu lösen.

Ich verwende das ganze auf der Website einer Band, die dann ihre Samples selber hochladen können. Das ganze wird dann in die Datenbank eingetragen, und über ein anderes skript in die Playlist eines Flash-Mp3-Players eingetragen.

Zunächst erstmal. Das input-feld bekommt NICHT den gleichen Namen! Der name des input-feldes wird nur benötigt, falls der User kein Javascript oder Flash benutzen kann. In dem Fall wird die Datei von der Seite bearbeitet, and die das Formular gesendet wird. Also in diesem Fall die thanks.php.

Sind Flash und Javascript aktiviert, dann wird die Datei von der upload.php bearbeitet. Alle anderen Formulardaten werden trotzdem von der thanks.php bearbeitet.

Zu dem Fehler. Ich glaube der Fehler wird immer ausgegeben, wenn die upload.php nicht gefunden wird, oder einen Fehler produziert.

Auf http://www.swfupload.org kann man sich das ganze runterladen, und da sind auch alle demos dabei. Allerdings wird die Datei dort nicht verarbeitet, daher muss man die upload.php noch überarbeiten.

Mein Formular:
Code:
	<link href="swfupload/default.css" rel="stylesheet" type="text/css" />
	<script type="text/javascript" src="swfupload/swfupload.js"></script>
	<script type="text/javascript" src="swfupload/swfupload.graceful_degradation.js"></script>
	<script type="text/javascript" src="swfupload/handlers.js"></script>
	<script type="text/javascript">
		var swf_upload_control;

        window.onload = function () {
            swf_upload_control = new SWFUpload({
				// Backend settings
				upload_url: "http://www.deine-website.de/swfupload/upload.php",	// Relative to the SWF file, you can use an absolute URL as well.
				file_post_name: "resume_file",

				// Flash file settings
				file_size_limit : "10240",	// 10 MB
				file_types : "*.mp3",	// or you could use something like: "*.doc;*.wpd;*.pdf",
				file_types_description : "MP3-Dateien",
				file_upload_limit : "0", // Even though I only want one file I want the user to be able to try again if an upload fails
				file_queue_limit : "1", // this isn't needed because the upload_limit will automatically place a queue limit

				// Event handler settings
				swfupload_loaded_handler : myShowUI,
				
				//file_dialog_start_handler : fileDialogStart,		// I don't need to override this handler
				file_queued_handler : fileQueued,
				file_queue_error_handler : fileQueueError,
				file_dialog_complete_handler : fileDialogComplete,
				
				//upload_start_handler : uploadStart,	// I could do some client/JavaScript validation here, but I don't need to.
				upload_progress_handler : uploadProgress,
				upload_error_handler : uploadError,
				upload_success_handler : uploadSuccess,
				upload_complete_handler : uploadComplete,

				// Flash Settings
				flash_url : "swfupload/swfupload_f9.swf",	// Relative to this file

				// UI settings
				swfupload_element_id : "flashUI",		// setting for the graceful degradation plugin
				degraded_element_id : "degradedUI",

				custom_settings : {
					progress_target : "fsUploadProgress",
					upload_successful : false
				},
				
				// Debug settings
				debug: false
			});

        }

        function myShowUI() {
            var btnSubmit = document.getElementById("btnSubmit");
			var txtSongCreator = document.getElementById("songcreator");
			var txtSongTitle = document.getElementById("songtitle");
			var txtSongInfoLink = document.getElementById("songinfolink");
			
			btnSubmit.onclick = doSubmit;
			btnSubmit.disabled = true;


			txtSongCreator.onchange = validateForm;
			txtSongTitle.onchange = validateForm;
			
            SWFUpload.swfUploadLoaded.apply(this);  // Let SWFUpload finish loading the UI.
			validateForm();
        }
		
		function validateForm() {
			var txtFileName = document.getElementById("txtFileName");
			var txtSongCreator = document.getElementById("songcreator");
			var txtSongTitle = document.getElementById("songtitle");
			
			var is_valid = true;
			if (txtFileName.value === "") is_valid = false;
			if (txtSongCreator.value === "") is_valid = false;
			if (txtSongTitle.value === "") is_valid = false;
			
			document.getElementById("btnSubmit").disabled = !is_valid;
		
		}
		
		function fileBrowse() {
			var txtFileName = document.getElementById("txtFileName");
			txtFileName.value = "";

			this.cancelUpload();
			this.selectFile();
		}
		
		
        // Called by the submit button to start the upload
		function doSubmit(e) {
			e = e || window.event;
			if (e.stopPropagation) e.stopPropagation();
			e.cancelBubble = true;
			document.getElementById("btnSubmit").disabled = true;
      document.getElementById("songcreator").disabled = true;
      document.getElementById("songtitle").disabled = true;
			
			try {
				swf_upload_control.startUpload();
			} catch (ex) {

            }
            return false;
	    }

		 // Called by the queue complete handler to submit the form
	    function uploadDone() {
			try {
      document.getElementById("songcreator").disabled = false;
      document.getElementById("songtitle").disabled = false;
				document.forms[0].submit();
			} catch (ex) {
				alert("Error submitting form");
			}
	    }
	</script>

<h1>MP3 hochladen</h1>

	<form id="form1" action="thanks.php" enctype="multipart/form-data" method="post">
<p>
							<div id="flashUI" style="display: none;">
								<!-- The UI only gets displayed if SWFUpload loads properly -->
								<div>
									<input type="text" id="txtFileName" disabled="true" style="border: solid 1px; background-color: #FFFFFF;" /><input id="btnBrowse" type="button" value="MP3 ausw&auml;hlen..." onclick="fileBrowse.apply(swf_upload_control)" /> (10 MB max)
								</div>
								<div id="fsUploadProgress">
									<!-- This is where the file progress gets shown.  SWFUpload doesn't update the UI directly.
										The Handlers (in handlers.js) process the upload events and make the UI updates -->
								</div>
								<input type="hidden" name="hidFileID" id="hidFileID" value="" /><!-- This is where the file ID is stored after SWFUpload uploads the file and gets the ID back from upload.php -->
							</div>
							<div id="degradedUI">
								<!-- This is the standard UI.  This UI is shown by default but when SWFUpload loads it will be
								hidden and the "flashUI" will be shown -->
								<input type="file" name="resume_degraded" id="resume_degraded" /> (10 MB max)<br/>
							</div>
						Interpret:<br />
						<input id="songcreator" name="songcreator" style="width:400px;" value=""><br />
						Titel:<br />
						<input id="songtitle" name="songtitle" style="width:400px;" value=""><br />
						<br />
				<input type="submit" value="Datei hochladen" id="btnSubmit" />
</p>
	</form>

Die upload.php musste ich mit absolutem Pfad angeben, da ich es nur so für opera und ie kompatibel bekommen habe.
Bei "file_post_name" wird die Variable für $_FILES der upload.php angegeben.
Zulässige Dateitypen werden bei "file_types" angegeben. Bei mir nur *.mp3, da ich das ganze über eine Datenbank in die Playlist eines Flash-MP3-Players eintragen lasse.
Es funktioniert aber auch *.* dann sollte aber auch "file_types_description" in "Alle Dateien" geändert werden.

Meine upload.php
Code:
<?php
	if (isset($_FILES["resume_file"]) && is_uploaded_file($_FILES["resume_file"]["tmp_name"]) && $_FILES["resume_file"]["error"] == 0) {
  
  $filename = utf8_decode($_FILES["resume_file"]["name"]);

  // individuellen Dateinamen schaffen
  if(file_exists('../mp3player/'.$filename)){
  $i = 1;
  while (file_exists('../mp3player/'.$i.'_'.$filename)) { $i++; }
  $filename = $i.'_'.$filename;
  }

		echo $filename;	

    move_uploaded_file($_FILES["resume_file"]["tmp_name"], "../mp3player/".$filename);
	} else {
		echo ' '; // I have to return something or SWFUpload won't fire uploadSuccess
	}
?>

SWFUpload codiert den Dateinamen in utf8. Ich decodiere die in diesem Script wieder, damit die mit original-dateinamen auf dem server landen.
Dann wird nurnoch ein induvidueller Dateiname geschaffen, damit keine Datei überschrieben wird.
Und dann wird die Datei auf den Server kopiert.
echo $filename; ist wichtig, da der Dateiname da sich alles was dieses script ausgibt über $_POST["hidFileID"] (der name des hidden-input-feldes) an die thanks.php gesendet wird.

meine thanks.php
Code:
// Check for a degraded file upload, this means SWFUpload did not load and the user used the standard HTML upload
$used_degraded = false;
$resume_id = "";
if (isset($_FILES["resume_degraded"]) && is_uploaded_file($_FILES["resume_degraded"]["tmp_name"]) && $_FILES["resume_degraded"]["error"] == 0) {
    $filename = $_FILES["resume_degraded"]["name"];
    $used_degraded = true;
}

// Check for the file id we should have gotten from SWFUpload
if (isset($_POST["hidFileID"]) && $_POST["hidFileID"] != "" ) {
	$filename = $_POST["hidFileID"];
  $datei_ok = true;
}

if ($used_degraded) {

  // individuellen Dateinamen schaffen
  if(file_exists('mp3player/'.$filename)){
  $i = 1;
  while (file_exists('mp3player/'.$i.'_'.$filename)) { $i++; }
  $filename = $i.'_'.$filename;
  }

  $tempname = $_FILES['resume_degraded']['tmp_name'];
  $filetype = $_FILES['resume_degraded']['type']; 
  $filesize = $_FILES['resume_degraded']['size'];
  $max_size = 10485760; // in Bytes
  
  // Datei überprüfen
  if ($filesize > "$max_size") { // wenn Datei zu groß is
      echo "Die Datei $filename ist zu gro&szlig;!<br />Maximale Dateigr&ouml;&szlig;e beträgt ".($max_size / 1024)." KByte!"; 
  } elseif (!move_uploaded_file($tempname, "mp3player/".$filename)) { // Datei kopieren
      echo "Die Datei $filename wurde nicht &uuml;bertragen!"; 
  } else { // Datei is okay und kopiert
  $datei_ok = true;
  }
}

if ($datei_ok){

  // in Datenbank eintragen
  $insert = mysql_query("INSERT $audiotable (songlocation, songcreator, songtitle, songinfolink) VALUES ('".$filename."','".$_POST['songcreator']."','".$_POST['songtitle']."','".$_POST['songinfolink']."')", $db_connect) or die("Fehler2: ".mysql_error());  
echo "datei okay";
  
} // end of else ($datei_ok)

Erstmal wird überprüft ob SWFupload benutzt wurde oder nicht. Wenn ja ist "resume_degraded" leer. Wenn nicht, dann wird die Datei hier verarbeitet.
Wenn die Datei erfolgreich hochgeladen wurde, dann wird alles in die Datenbank eingetragen.

Und zur vervollständigung hier noch meine handlers.js. Da hab ich aber nur ein paar effekte hinzugefügt, sollte also auch mit der originalen handlers.js funktionieren.
Code:
function fileQueueError(fileObj, error_code, message)  {
	try {
		// Handle this error separately because we don't want to create a FileProgress element for it.
		switch(error_code) {
			case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED:
				alert("You have attempted to queue too many files.\n" + (message == 0 ? "You have reached the upload limit." : "You may select " + (message > 1 ? "up to " + message + " files." : "one file.")));
				return;
				break;
			case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
				alert("The file you selected is too big.");
				this.debug("Error Code: File too big, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
				return;
				break;
			case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
				alert("The file you selected is empty.  Please select another file.");
				this.debug("Error Code: Zero byte file, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
				return;
				break;
			case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
				alert("The file you choose is not an allowed file type.");
				this.debug("Error Code: Invalid File Type, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
				return;
				break;
			default:
				alert("An error occurred in the upload. Try again later.");
				this.debug("Error Code: " + error_code + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
				return;
				break;
		}
	} catch (e) {}
}

function fileQueued(fileObj) {
	try {
		var txtFileName = document.getElementById("txtFileName");
		txtFileName.value = fileObj.name;
	} catch (e) { }

}
function fileDialogComplete(num_files_selected) {
	validateForm();
}

function uploadProgress(fileObj, bytesLoaded, bytesTotal) {

	try {
		var percent = Math.ceil((bytesLoaded / bytesTotal) * 100)

		fileObj.id = "singlefile";	// This makes it so FileProgress only makes a single UI element, instead of one for each file
		var progress = new FileProgress(fileObj, this.customSettings.progress_target);
		progress.SetProgress(percent);
		progress.SetStatus("Uploading...");
	} catch (e) { }
}

function uploadSuccess(fileObj, server_data) {
	try {
		fileObj.id = "singlefile";	// This makes it so FileProgress only makes a single UI element, instead of one for each file
		var progress = new FileProgress(fileObj, this.customSettings.progress_target);
		progress.SetComplete();
		progress.SetStatus("Complete.");
		progress.ToggleCancel(false);
		
		if (server_data === " ") {
			this.customSettings.upload_successful = false;
		} else {
			this.customSettings.upload_successful = true;
			document.getElementById("hidFileID").value = server_data;
		}
		
	} catch (e) { }
}

function uploadComplete(fileObj) {
	try {
		if (this.customSettings.upload_successful) {
			document.getElementById("btnBrowse").disabled = "true";
			uploadDone();
		} else {
			fileObj.id = "singlefile";	// This makes it so FileProgress only makes a single UI element, instead of one for each file
			var progress = new FileProgress(fileObj, this.customSettings.progress_target);
			progress.SetError();
			progress.SetStatus("File rejected");
			progress.ToggleCancel(false);
			
			var txtFileName = document.getElementById("txtFileName");
			txtFileName.value = "";
			validateForm();

			alert("There was a problem with the upload.\nThe server did not accept it.");
		}
	} catch (e) {  }
}

function uploadError(fileObj, error_code, message) {
	try {
		var txtFileName = document.getElementById("txtFileName");
		txtFileName.value = "";
		validateForm();
		
		// Handle this error separately because we don't want to create a FileProgress element for it.
		switch(error_code) {
			case SWFUpload.UPLOAD_ERROR.MISSING_UPLOAD_URL:
				alert("There was a configuration error.  You will not be able to upload a resume at this time.");
				this.debug("Error Code: No backend file, File name: " + file.name + ", Message: " + message);
				return;
				break;
			case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
				alert("You may only upload 1 file.");
				this.debug("Error Code: Upload Limit Exceeded, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
				return;
				break;
			case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
			case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
				break;
			default:
				alert("An error occurred in the upload. Try again later.");
				this.debug("Error Code: " + error_code + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
				return;
				break;
		}

		fileObj.id = "singlefile";	// This makes it so FileProgress only makes a single UI element, instead of one for each file
		var progress = new FileProgress(fileObj, this.customSettings.progress_target);
		progress.SetError();
		progress.ToggleCancel(false);

		switch(error_code) {
			case SWFUpload.UPLOAD_ERROR.HTTP_ERROR:
				progress.SetStatus("Upload Error");
				this.debug("Error Code: HTTP Error, File name: " + file.name + ", Message: " + message);
				break;
			case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED:
				progress.SetStatus("Upload Failed.");
				this.debug("Error Code: Upload Failed, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
				break;
			case SWFUpload.UPLOAD_ERROR.IO_ERROR:
				progress.SetStatus("Server (IO) Error");
				this.debug("Error Code: IO Error, File name: " + file.name + ", Message: " + message);
				break;
			case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR:
				progress.SetStatus("Security Error");
				this.debug("Error Code: Security Error, File name: " + file.name + ", Message: " + message);
				break;
			case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
				progress.SetStatus("Upload Cancelled");
				this.debug("Error Code: Upload Cancelled, File name: " + file.name + ", Message: " + message);
				break;
			case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
				progress.SetStatus("Upload Stopped");
				this.debug("Error Code: Upload Stopped, File name: " + file.name + ", Message: " + message);
				break;
		}
	} catch (e) {}
}


/* ********************************************************
 *  Utility for displaying the file upload information
 *  This is not part of SWFUpload, just part of the demo
 * ******************************************************** */
function FileProgress(fileObj, target_id) {
	this.file_progress_id = fileObj.id;

	this.fileProgressWrapper = document.getElementById(this.file_progress_id);
	if (!this.fileProgressWrapper) {
		this.fileProgressWrapper = document.createElement("div");
		this.fileProgressWrapper.className = "progressWrapper";
		this.fileProgressWrapper.id = this.file_progress_id;

		this.fileProgressElement = document.createElement("div");
		this.fileProgressElement.className = "progressContainer";

		var progressCancel = document.createElement("a");
		progressCancel.className = "progressCancel";
		progressCancel.href = "#";
		progressCancel.style.visibility = "hidden";
		progressCancel.appendChild(document.createTextNode(" "));

		var progressText = document.createElement("div");
		progressText.className = "progressName";
		progressText.appendChild(document.createTextNode(fileObj.name));

		var progressBar = document.createElement("div");
		progressBar.className = "progressBarInProgress";

		var progressStatus = document.createElement("div");
		progressStatus.className = "progressBarStatus";
		progressStatus.innerHTML = "&nbsp;";

		this.fileProgressElement.appendChild(progressCancel);
		this.fileProgressElement.appendChild(progressText);
		this.fileProgressElement.appendChild(progressStatus);
		this.fileProgressElement.appendChild(progressBar);

		this.fileProgressWrapper.appendChild(this.fileProgressElement);

		document.getElementById(target_id).appendChild(this.fileProgressWrapper);
    FadeIn(this.fileProgressWrapper, 0, 0);

	} else {
		this.fileProgressElement = this.fileProgressWrapper.firstChild;
	}

}
FileProgress.prototype.SetProgress = function(percentage) {
	this.fileProgressElement.className = "progressContainer green";
	this.fileProgressElement.childNodes[3].className = "progressBarInProgress";
	this.fileProgressElement.childNodes[3].style.width = percentage + "%";
};
FileProgress.prototype.SetComplete = function() {
	this.fileProgressElement.className = "progressContainer blue";
	this.fileProgressElement.childNodes[3].className = "progressBarComplete";
	this.fileProgressElement.childNodes[3].style.width = "";

};
FileProgress.prototype.SetError = function() {
	this.fileProgressElement.className = "progressContainer red";
	this.fileProgressElement.childNodes[3].className = "progressBarError";
	this.fileProgressElement.childNodes[3].style.width = "";

};
FileProgress.prototype.SetCancelled = function() {
	this.fileProgressElement.className = "progressContainer";
	this.fileProgressElement.childNodes[3].className = "progressBarError";
	this.fileProgressElement.childNodes[3].style.width = "";

};
FileProgress.prototype.SetStatus = function(status) {
	this.fileProgressElement.childNodes[2].innerHTML = status;
};

FileProgress.prototype.ToggleCancel = function(show, upload_obj) {
	this.fileProgressElement.childNodes[0].style.visibility = show ? "visible" : "hidden";
	if (upload_obj) {
		var file_id = this.file_progress_id;
		this.fileProgressElement.childNodes[0].onclick = function() { upload_obj.cancelUpload(file_id); return false; };
	}
};

function FadeIn(element, opacity, height) {
	var reduce_opacity_by = 10;
  var reduce_height_by = 5;
	var rate = 30;	// 15 fps


	if (opacity < 100) {
		opacity += reduce_opacity_by;
		if (opacity > 100) opacity = 100;

		if (element.filters) {
			try {
				element.filters.item("DXImageTransform.Microsoft.Alpha").opacity = opacity;
			} catch (e) {
				// If it is not set initially, the browser will throw an error.  This will set it if it is not set yet.
				element.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + opacity + ')';
			}
		} else {
			element.style.opacity = opacity / 100;
		}
	}

	if (height < 50) {
		height += reduce_height_by;
		if (height > 50) {
			height = 50;
		}

		element.style.height = height + "px";
	}

	if (height < 50 || opacity < 100) {
		setTimeout(function() { FadeIn(element, opacity, height); }, rate);
	}
}

Das Formular und die thanks.php liegen dabei im Hauptordner, und alle anderen Dateien im Unterordner "swfupload". Und die Datei wird in den Ordner "mp3player" kopiert, der natürlich entsprechende Schreibrechte haben muss.

Ich hoffe damit helfen zu können.
 
hab deinen code ausprobiert, aber ich bekomme keine optische darstellung des uploads... der rest funktioniert... was mache ich da falsch?
 
hab deinen code ausprobiert, aber ich bekomme keine optische darstellung des uploads... der rest funktioniert... was mache ich da falsch?

Der gepostete Code ist schon etwas älter, ich weiß jetzt nicht ob es da Änderungen mit neueren Versionen von SWFupload gegeben hat.

Es wär erstmal interessant zu wissen, ob die Datei bei dir über die resume_degraded-Funktion verarbeitet wird, oder über die upload.php.

Das kannst du relativ leicht rausfinden, indem du z.B. bei der upload.php und der resume_degraded-Funktion verschiedene Zielverzeichnisse angibst, und dann guckst in welchem Ordner die Datei landet.

Oder noch einfacher:
Du änderst einfach die Zeile
if ($used_degraded) {
in
if ($used_degraded) { echo "degraded";
wenn dann am Ende der Text "degraded" erscheint, dann wurde das ganze über resume_degraded hochgeladen.

Benutzt du die originale handlers.js aus der Demo, oder die die ich gepostet habe?
 
Zuletzt bearbeitet:
Zurück