Instantly share code, notes, and snippets.

Embed
What would you like to do?
Code from Tutorial: Uploading Files Demystified (http://coronalabs.com/blog/2014/02/25/tutorial-uploading-files-demystified/)
-- Callback function to handle the upload events that are generated.
-- There will be several events: one to indicate the start and end of the
-- process and several to indicate the progress (depends on the file size).
-- Always test for your error conditions!
local function uploadListener( event )
if ( event.isError ) then
print( "Network Error." )
-- This is likely a time out or server being down. In other words,
-- It was unable to communicate with the web server. Now if the
-- connection to the web server worked, but the request is bad, this
-- will be false and you need to look at event.status and event.response
-- to see why the web server failed to do what you want.
else
if ( event.phase == "began" ) then
print( "Upload started" )
elseif ( event.phase == "progress" ) then
print( "Uploading... bytes transferred ", event.bytesTransferred )
elseif ( event.phase == "ended" ) then
print( "Upload ended..." )
print( "Status:", event.status )
print( "Response:", event.response )
end
end
end
-- Sepcify the URL of the PHP script to upload to. Do this on your own server.
-- Also define the method as "PUT".
local url = "http://yourwebserver.com/somepath/upload.php"
local method = "PUT"
-- Set some reasonable parameters for the upload process:
local params = {
timeout = 60,
progress = true,
bodyType = "binary"
}
-- Specify what file to upload and where to upload it from.
-- Also, set the MIME type of the file so that the server knows what to expect.
local filename = "image.jpg"
local baseDirectory = system.ResourceDirectory
local contentType = "image/jpeg" --another option is "text/plain"
-- There is no standard way of using HTTP PUT to tell the remote host what
-- to name the file. We'll make up our own header here so that our PHP script
-- expects to look for that and provides the name of the file. Your PHP script
-- needs to be "hardened" because this is a security risk. For example, someone
-- could pass in a path name that might try to write arbitrary files to your
-- server and overwrite critical system files with malicious code.
-- Don't assume "This won't happen to me!" because it very well could.
local headers = {}
headers.filename = filename
params.headers = headers
network.upload( url , method, uploadListener, params, filename, baseDirectory, contentType )
<?php
// upload.php
// Simple File uploader using HTTP PUT
//
// This app makes several assumptions:
// 1. You have a folder named "upload" that is a child folder where this script resides.
// 2. The web server has the ability to create files in that folder. You have to make sure permissions
// are correct.
// 3. Your web server allows this to work.
// 4. This script will live in a folder that does not have write permission.
// 5. You understand the perils of allowing scripts to run on your web server that allow people to
// write arbitrary files that you don't have control over.
//
// Please read and understand all of the information here:
// http://www.php.net/manual/en/features.file-upload.php
// before going into production with this. Expect to spend time getting this right.
//
// Code to handle sending back HTTP response codes. See:
// http://stackoverflow.com/questions/3258634/php-how-to-send-http-response-code
// for more information.
//
// For 4.3.0 <= PHP <= 5.4.0
if (!function_exists('http_response_code'))
{
function http_response_code($newcode = NULL)
{
static $code = 200;
if($newcode !== NULL)
{
header('X-PHP-Response-Code: '.$newcode, true, $newcode);
if(!headers_sent())
$code = $newcode;
}
return $code;
}
}
//
// This is an arbitary limit. Your PHP server has it's own limits, which may be more or
// less than this limit. Consider this an exercise in learning more about how your PHP
// server is configured. If it allows less, then your script will fail.
//
// See: http://stackoverflow.com/questions/2184513/php-change-the-maximum-upload-file-size
// for more information on file size limits.
//
$MAX_FILESIZE = 5 * 1024 * 1024; // 5 megabyte limit -- arbitrary value based on your needs
if ((isset($_SERVER["HTTP_FILENAME"])) && (isset($_SERVER["CONTENT_TYPE"])) && (isset($_SERVER["CONTENT_LENGTH"]))) {
$filesize = $_SERVER["CONTENT_LENGTH"];
// get the base name of the file. This should remove any path information, but like anything
// that writes to your file server, you may need to take extra steps to harden this to make sure
// there are no path remnants in the file name.
//
$filename = basename($_SERVER["HTTP_FILENAME"]);
$filetype = $_SERVER["CONTENT_TYPE"];
//
// enforce the arbirary file size limits here
//
if ($filesize > $MAX_FILESIZE) {
http_response_code(413);
echo("File too large");
exit;
}
//
// Make sure the filename is unique.
// This will cause files after 100 of the same name to overwrite each other.
// And it won't notify you. Don't depend on this logic for production.
// You should code this to fit your needs.
//
if (file_exists("upload/" . $filename)) {
//echo("duplicate filename");
$i = 1;
$path_parts = pathinfo($filename);
$filename = $path_parts['filename'] . "_" . $i . "." . $path_parts['extension'];
while(file_exists("upload/" . $filename)) {
$i++;
if ($i > 100) {
break;
}
$filename = $path_parts['filename'] . "_" . $i . "." . $path_parts['extension'];
}
}
/* PUT data comes in on the stdin stream */
$putdata = fopen("php://input", "r");
if ($putdata) {
/* Open a file for writing */
$tmpfname = tempnam("upload", "myapp");
$fp = fopen($tmpfname, "w");
if ($fp) {
/* Read the data 1 KB at a time and write to the file */
while ($data = fread($putdata, 1024)) {
fwrite($fp, $data);
}
/* Close the streams */
fclose($fp);
fclose($putdata);
$result = rename($tmpfname, "upload/" . $filename);
if ($result) {
http_response_code(201);
echo("File Created " . $filename);
} else {
http_response_code(403);
echo("Renaming file to upload/" . $filename . " failed.");
}
} else {
http_response_code(403);
echo("Could not open tmp file " . $tmpfname);
}
} else {
http_response_code(403);
echo("Could not read upload stream.");
}
} else {
http_response_code(500);
echo("Malformed Request");
}
?>
@techClick

This comment has been minimized.

Copy link

techClick commented Mar 2, 2018

Hi,
I tried this but the "PUT" method always returns network error on my corona device.

EDIT: Is there a way I can go about this, because using "POST" method, I get the error("Renaming file to upload/" . $filename . " failed."). What must I do?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment