Saving a file inside the application's memory - php

I am trying to download a file from a php get url that has username and password. My code doesn't show any errors and the progress bar shows me that the file is downloaded but when I try to print the list inside the Log I cannot see the file. What am I doing wrong?
That's the code inside the doInBackground section in the AsyncTask which I have called inside the onCreate and have put the url inside the parameters.
protected String doInBackground(String... sUrl) {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try{
URL url = new URL(sUrl[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
int fileLength = connection.getContentLength();
input = connection.getInputStream();
output = new FileOutputStream(context.getFilesDir()+"video.m3u");
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1){
total = total + count;
if (fileLength > 0){
publishProgress((int) (total * 100 / fileLength));
}
output.write(data, 0, count);
}
}catch (Exception e){
return e.toString();
}finally {
try{
if (output != null){
output.close();
}
if (input != null){
input.close();
}
}catch (IOException ignored){
}
if (connection != null){
connection.disconnect();
}
}
return "";
}
In the onPostExecute section I have written this code
if (result.equals("")){
String path = context.getFilesDir().toString();
Log.d("Files", "Path: "+ path);
File directory = new File(path);
File[] files = directory.listFiles();
Log.d("Files", "Size: " + files.length);
for (int i = 0; i<files.length; i++){
Log.d("Files", "File Name: " + files[i].getName());
}
}
But the only thing that I get printed is this:
D/Files: Path: /data/data/my.app.package/files
D/Files: Size: 1
D/Files: File Name: instant-run
I can't see the file that has been downloaded.

I think the problem is this line
output = new FileOutputStream(context.getFilesDir()+"video.m3u");
context.getFilesDir() doesn't return String, it's File object you need to do this
output = new FileOutputStream(context.getFilesDir()..getAbsolutePath()+"/video.m3u");

The file path you are saving to is wrong. Right now you are saving to
output = new FileOutputStream(context.getFilesDir()+"video.m3u");
it needs to be output = new FileOutputStream(context.getFilesDir().getAbsolutePath()+"/video.m3u");
Hopes this helps.

Related

PHP can not find files in windows

I have build a server use PHP based on WAMP Server on my windows 10 computer. what I want to do is when I send a GET request, the show_files.php should return a JSON object to me. The JSON object contains file names in path F:\NetEaseMusic\download on my computer. Then I use a file name to send a POST request to download_file.php and it returns a data stream so that I can download file. When I use HttpURLConnection, everything works well. However, when I try send the POST request use socket, download_file.php can get the file_name param, but it can not find the target file in F:\NetEaseMusic\download. I show the code.
this is
this is download_file.php
<?php
if(empty($_POST["file_name"]))
{
echo "NO_FILE_NAME\n";
print_r($_POST);
exit();
}
$path = iconv("utf-8", "GB2312","F:\\NetEaseMusic\\download\\".$_POST["file_name"]);
//$path = "F:\\NetEaseMusic\\download\\".$_POST["file_name"];
if (!file_exists ( $path )) {
echo "FILE_NOT_FOUND\n";
echo "F:\\NetEaseMusic\\download\\".$_POST["file_name"]."\n";
print($path);
exit ();
}
$file_size = filesize($path);
//header("Content-type: application/octet-stream");
//header("Accept-Ranges: bytes");
//header("Accept-Length:".$file_size);
//header("Content-Disposition: attachment; filename=".$path);
$file = fopen($path, "r");
while(!feof($file))
{
echo fread($file, 1024);
}
exit();
?>
this is my Client code which to download file. First of all I build a HTTP POST request,
private void downloadFileBySocket(String urlString, String fileName)
{
try{
StringBuilder sb = new StringBuilder();
String data = URLEncoder.encode("file_name", "utf-8") + "=" + URLEncoder.encode(fileName, "utf-8") + "\r\n";
//String data = "&file_name="+fileName;
sb.append("POST " + urlString + " HTTP/1.1\r\n");
sb.append("Host: 10.206.68.242\r\n");
sb.append("Content-Type: application/x-www-form-urlencoded\r\n");
sb.append("Content-Length: " + data.length() + "\r\n");
sb.append("\r\n");
sb.append(data + "\r\n");
//sb.append( URLEncoder.encode("file_name", "utf-8") + "=" + URLEncoder.encode(fileName, "utf-8") + "\r\n");
System.out.println(sb.toString());
URL url = new URL(urlString);
Socket socket = new Socket(url.getHost(), url.getPort());
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "utf-8"));
writer.write(sb.toString());
writer.flush();
File file = new File("./" + fileName);
DataOutputStream out = null;
DataInputStream in = null;
try{
out = new DataOutputStream(new FileOutputStream(file));
in = new DataInputStream(socket.getInputStream());
byte[] buffer = new byte[1024];
int readBytes = 0;
while((readBytes = in.read(buffer)) != -1)
{
out.write(buffer, 0, readBytes);
}
out.flush();
}catch (Exception e1)
{
e1.printStackTrace();
}finally {
try{
if(in != null)
{
in.close();
}
if(out != null)
{
out.close();
}
}catch (Exception e2)
{
e2.printStackTrace();
}
}
socket.close();
}catch (Exception e)
{
e.printStackTrace();
}
}
and my main[] method
public static void main(String[] args)
{
SocketTest socketTest = new SocketTest();
socketTest.downloadFileBySocket(SocketTest.downloadFileUrl, "小胡仙儿 - 【二胡】霜雪千年.mp3");
}
Simple way:
using System.Net;
WebClient webClient = new WebClient();
webClient.DownloadFile("example.com/myfile.txt", #"c:/myfile.txt");

android upload image file into PHP server

I took this code on Internet. I can upload image file to Server successful. However, the image files cannot be opened. I think the content of the files has problem after uploading. Can anybody help me please? Thank you very much
public static void put(String targetURL, File file, String username, String password) throws Exception {
String BOUNDRY = "==================================";
HttpURLConnection conn = null;
try {
// Make a connect to the server
URL url = new URL(targetURL);
conn = (HttpURLConnection) url.openConnection();
if (username != null) {
String usernamePassword = username + ":" + password;
//String encodedUsernamePassword = Base64.encodeBytes(usernamePassword.getBytes());
String encodedUsernamePassword = String.valueOf(Base64.encodeBase64(usernamePassword.getBytes()));
conn.setRequestProperty ("Authorization", "Basic " + encodedUsernamePassword);
}
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+BOUNDRY);
DataOutputStream dataOS = new DataOutputStream(conn.getOutputStream());
dataOS.writeBytes("--");
dataOS.writeBytes(BOUNDRY);
dataOS.writeBytes("\n");
dataOS.writeBytes("Content-Disposition: form-data; name=\"fileToUpload\"; fileName=\"" + file.getName() +"\"" + "\n");
dataOS.writeBytes("\n");
dataOS.writeBytes(new String(getBytesFromFile(file)));
dataOS.writeBytes("\n");
dataOS.writeBytes("--");
dataOS.writeBytes(BOUNDRY);
dataOS.writeBytes("--");
dataOS.writeBytes("\n");
dataOS.flush();
dataOS.close();
int responseCode = conn.getResponseCode();
if (responseCode != 200) {
throw new Exception(String.format("Received the response code %d from the URL %s", responseCode, url));
}
InputStream is = conn.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] bytes = new byte[4096];
int bytesRead;
while((bytesRead = is.read(bytes)) != -1) {
baos.write(bytes, 0, bytesRead);
}
byte[] bytesReceived = baos.toByteArray();
baos.close();
is.close();
String response = new String(bytesReceived);
} finally {
if (conn != null) {
conn.disconnect();
}
}
}
public static byte[] getBytesFromFile(File file) throws IOException {
InputStream is = new FileInputStream(file);
// Get the size of the file
long length = file.length();
// You cannot create an array using a long type.
// It needs to be an int type.
// Before converting to an int type, check
// to ensure that file is not larger than Integer.MAX_VALUE.
if (length > Integer.MAX_VALUE) {
// File is too large
}
// Create the byte array to hold the data
byte[] bytes = new byte[(int)length];
// Read in the bytes
int offset = 0;
int numRead = 0;
while (offset < bytes.length
&& (numRead = is.read(bytes, offset, Math.min(bytes.length - offset, 512*1024))) >= 0) {
offset += numRead;
}
// Ensure all the bytes have been read in
if (offset < bytes.length) {
throw new IOException("Could not completely read file "+file.getName());
}
// Close the input stream and return bytes
is.close();
return bytes;
}
And the bellow is my code in PHP:
$target = "/upload/";
$target = $target . basename( $_FILES['fileToUpload']['name']) ;
if(move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target)) {
echo "The file ". basename( $_FILES['fileToUpload']['name']). " has been uploaded";
$result['login'] = true;
}else {
$result['login']=false;
echo "Sorry, there was a problem uploading your file.";
}
$json = json_encode($result, JSON_PRETTY_PRINT);
print_r($json);
Maybe problem occur when you set Content-Type, try remove this
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+BOUNDRY);

PHP image encoding not working

I'm trying to encode a .jpg file on my server and send the string back to my android app. The PHP encoding function doesn't seem to be working - I always get a null response.
...
} else if ($tag == 'getPhoto') {
$filePath = $_POST['filePath'];
$filePath = mysql_real_escape_string($filePath);
$photo_str = $db->getPhotoString($filePath);
$photo_str = mysql_real_escape_string($photo_str);
if (!empty($photo_str)) {
echo $photo_str;
} else {
echo 'Something went wrong while retrieving the photo.';
}
}
...
public function getPhotoString($filePath) {
$type = pathinfo($filePath, PATHINFO_EXTENSION);
$photoData = file_get_contents($filePath);
$photo_str = 'data:image/' . $type . ';base64,' . base64_encode($photoData);
// $photo_str = 'test_response';
return $photo_str;
}
I know my filepath is correct because when I change it I get an error that says the file/directory doesn't exist. And, the "test_response" works when I uncomment it. Please help!
UPDATE - relevant android code:
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(parameters));
HttpResponse response = httpClient.execute(httpPost);
photoString = convertResponseToString(response);
Log.d("string response", photoString);
public String convertResponseToString(HttpResponse response) throws IllegalStateException, IOException{
String res = "";
StringBuffer buffer = new StringBuffer();
is = response.getEntity().getContent();
int contentLength = (int) response.getEntity().getContentLength(); //getting content length…..
if (contentLength < 0) {
} else {
byte[] data = new byte[512];
int len = 0;
try {
while (-1 != (len = is.read(data))) {
buffer.append(new String(data, 0, len)); //converting to string and appending to stringbuffer…..
}
} catch (IOException e) {
e.printStackTrace();
}
try {
is.close(); // closing the stream…..
} catch (IOException e) {
e.printStackTrace();
}
res = buffer.toString(); // converting stringbuffer to string…..
}
//System.out.println("Response => " + EntityUtils.toString(response.getEntity()));
return res;
}
This is not an answer, only a suggestion but i'm not able to comment as i don't have enough reputation xD. Anyway, did you try to echo $photoData after
$photoData = file_get_contents($filePath);
to see if it's filled with something? Maybe you get a null result. Also, can you tell me what's $filePath value when taken from $_POST variable and when passed to getPhotoString($filePath) function? I'm thinking about something wrong with mysql_real_escape_string().

Android: How to get image from remote server

I am developing an Android app that should get an image from remote server. Am using WAMP as my server and PHP as programming language. I know how to get text data using JSON.
Am not using blob to store image.
Images have stored in a folder on server. Url of image is stored in db table.
I tried the following snippet, I got this from net but it is not giving any error and also it is not displaying image
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://10.0.2.2/sareesProject/returnSareeTypeImageUrls.php");
response = httpClient.execute(httpPost);
entity = response.getEntity();
if(response.getStatusLine().getStatusCode() == 200)
{
Log.d("Http Response:", response.toString());
if(entity != null)
{
InputStream instream = entity.getContent();
JSONObject jsonObj = new JSONObject(convertStreamToString(instream));
String base64Image = jsonObj.getString("pprs");
Toast.makeText(getBaseContext(), base64Image, Toast.LENGTH_LONG).show();
byte[] rawImage = Base64.decode(base64Image, Base64.DEFAULT);
bmp = BitmapFactory.decodeByteArray(rawImage, 0, rawImage.length);
}
}
ImageView imageview = (ImageView) findViewById(R.id.flag);
imageview.setImageBitmap(bmp);
The following is my php code
<?php
error_reporting( E_ALL ^ E_NOTICE ^ E_WARNING);
$con = mysql_connect("localhost","root","") or die("con error");
mysql_select_db("sareesdb") or die("db select eror");
$query = mysql_query("select * from noofpiecesinatype");
if($row = mysql_fetch_assoc($query))
{
$response = $row['imageUrl'];
}
$response = base64_encode($response);
echo '{"pprs":'.json_encode($response).'}';
mysqli_close($con);
?>
I checked my php code with html(with out encoding $response value) am getting image there, but not in Android.
I am not good with Php, but if you return the file url via a JSON reponse you can use the following code for downloading the file.
int count;
try {
URL url = new URL("http://url of your file");
URLConnection conection = url.openConnection();
conection.connect();
// getting file length
int lenghtOfFile = conection.getContentLength();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(), 8192);
// Output stream to write file
OutputStream output = new FileOutputStream("/sdcard/downloadedfile.jpg");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress(""+(int)((total*100)/lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
## Edit ##
After the Image is downloaded you can create a Bitmap from the Image Path/InputStream and assign it to the Image View like this
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
Bitmap bmp = BitmapFactory.decodeStream(bufferedInputStream);
Original source
try {
httpClient = new DefaultHttpClient();
httpPost = new HttpPost("http://10.0.2.2/sareesProject/returnSareeTypeImageUrls.php");
response = httpClient.execute(httpPost);
entity = response.getEntity();
if(response.getStatusLine().getStatusCode() == 200)
{
Log.d("Http Response:", response.toString());
if(entity != null)
{
instream = entity.getContent();
JSONObject jsonObj = new JSONObject(convertStreamToString(instream));
bitmapPath = jsonObj.getString("pprs");
}
}
try {
Toast.makeText(getBaseContext(), "http://10.0.2.2/sareesProject/"+bitmapPath, Toast.LENGTH_SHORT).show();
URL url = new URL("http://10.0.2.2/sareesProject/"+bitmapPath);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
bmp = myBitmap;
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getBaseContext(), e.getMessage(),Toast.LENGTH_SHORT).show();
}
if(bmp == null)
Toast.makeText(getBaseContext(), "null", Toast.LENGTH_SHORT).show();
ImageView imageview = (ImageView) findViewById(R.id.flag);
imageview.setImageBitmap(bmp);
} catch (Exception e) {
// TODO: handle exception
Toast.makeText(getBaseContext(),e.getMessage(), Toast.LENGTH_LONG).show();
}
private static String convertStreamToString(InputStream is) {
/*
* To convert the InputStream to String we use the BufferedReader.readLine()
* method. We iterate until the BufferedReader return null which means
* there's no more data to read. Each line will appended to a StringBuilder
* and returned as String.
*/
//new HomePage().show("in con");
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
//show(line);
//new HomePage().show("in while");
//new HomePage().show("l="+line);
sb.append(line+"\n");
}
} catch (IOException e) {
e.printStackTrace();
//Toast.makeText(, text, duration)
} finally {
try {
if(reader != null)
{
try{reader.close();}
catch(Exception e){e.printStackTrace();}
}
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}//end of convertStreamToString
The following is my php code
<?php
error_reporting( E_ALL ^ E_NOTICE ^ E_WARNING);
$con = mysql_connect("localhost","root","") or die("con error");
mysql_select_db("sareesdb") or die("db select eror");
$query = mysql_query("select * from noofpiecesinatype");
$response = array();
while($row = mysql_fetch_assoc($query))
{
$response[] = $row['imageUrl'];
}
echo json_encode($response);
mysqli_close($con);
?>
//--------------------
Fnally i got it.............
First of all my server file returns the following
{"pprs":"upload/22.png"}
from this i extracted upload/22.png using JSON
Now bitmapPath contains upload/22.png
Thank you very much to insomniac giving suggestions.............
If it is helpful to any one vote for me..............

Occasional incomplete uploads for large files with HttpPut and Apache PHP in Android

I have written Android code to upload a large file (10MB+) via HTTP Put to an Apache PHP server (I cannot use FTP because my application sometimes operates on mobile networks, and I hear many mobile carriers do not allow FTP-If I am wrong, please correct me). The function that handles the actual upload is called by an AsyncTask, so it does not cause the application to hang. However, I have some concerns about the method of uploading-sometimes I get incomplete uploads, sometimes with "false positives"-I get a signal back that the file uploaded, only to check and see nothing.
My background is deeper in C than Java and I'm not entirely clear about Java's automatic memory management, so if my questions seem somewhat ridiculous, forgive me.
So, here are my questions:
1) Might the upload problems be caused by memory issues? The code was originally written to read everything at once by the original developer, but I have re-written it below to use a ByteArrayOutputStream and read the file chunk by chunk. I still worry that the InputStream is trying to read everything at once on initialization. Am I just misunderstanding InputStream, or does it behave more like a File pointer in C?
2) I dislike calling new everytime in the while loop-I suspect that, like in C, new memory is being allocated all the time, but I am not sure if calling null before re-initialization really helps here. Is this causing a leak here? I only ask because I presume that Java's Memory Management somehow ensures not to allow more memory to the heap and keeps track of references.
3) The uploading stops if the phone goes into standby. Is there anyway to keep the upload moving when this happens?
4) Might the PHP server code be missing something in terms of reporting networking errors/issues? I have included as much as I can for handling write errors, but I feel somehow this could be written better.
Also, I am not constrained to using HttpPut-this was simply a method suggested to me. I am open to changing things on the server side to support a better method of file transfer.
Android Java code (function in upload client):
private boolean transmitBytes(Uri uri)
{
/**/
ByteArrayEntity requestEntity;
InputStream inputStream = null;
float temp = 0.0f;
float temp1 = 0.0f;
long total = 0;
int buffSize = 102400;
byte[] buffer;
try {
inputStream = getContentResolver().openInputStream(uri);
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
if (length <= 1048576) {
buffer = new byte[buffSize];
} else {
buffer = new byte[bufferSize];
}
// we need to know how may bytes were read to write them to the byteBuffer
int len = 0;
sharedPreferences = getSharedPreferences("Upload", MODE_PRIVATE);
String userid = sharedPreferences.getString("userid", ""); // Set the first segment with
// the resume flag at 0 so
// wipes anything of that
// filename on
// srvr.
String putURL = Constants.UPLOAD_MEDIA_URL;
putURL += "mediatype=";
putURL += mediatype;
putURL += "&file_name=";
putURL += new File(vidFileName).getName();
putURL += "&usrname=";
putURL += userid;
putURL += "&filesize=";
putURL += Long.toString(length);
putURL += "&sha256sum=";
putURL += cksum;
putURL += "&resume=0";
putURL = putURL.replace(" ", "");
// Read the first segment for transmission.
if ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
// Dump first segment into requestEntity
requestEntity = new ByteArrayEntity(byteBuffer.toByteArray());
// Wipe byte buffer after you are done writing with it to clear out contents.
byteBuffer.reset();
// Transmit segment.
HttpPut httpPut = new HttpPut(putURL);
httpPut.setEntity(requestEntity);
DefaultHttpClient httpClient = new DefaultHttpClient();
//Set timeouts. If no response by timeout, mark failure.
HttpParams httpParameters = new BasicHttpParams();
// The default value is zero, that means the timeout is not used and we go to infinite.
//Set to 3000 ms here.
int timeoutConnection = 5000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// in milliseconds which is the timeout for waiting for data. If not set, will be infinite.
int timeoutSocket = 5000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
httpClient.setParams(httpParameters);
// Transmit via PUT
HttpResponse response = httpClient.execute(httpPut);
HttpEntity entity = response.getEntity();
entity.getContent();
// Set resume tag to 1.
putURL = putURL.replaceAll("&resume=0", "&resume=1");
}
// write the remaining segments, (bufferSize) at a time
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
requestEntity = new ByteArrayEntity(byteBuffer.toByteArray());
// Wipe byte buffer after you are done writing with it to clear out contents.
byteBuffer.reset();
HttpPut httpPut = new HttpPut(putURL);
httpPut.setEntity(requestEntity);
DefaultHttpClient httpClient = new DefaultHttpClient();
//Set timeouts. If no response by timeout, mark failure.
HttpParams httpParameters = new BasicHttpParams();
// The default value is zero, that means the timeout is not used. Set to 3000 ms here.
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 5000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
httpClient.setParams(httpParameters);
// Transmit via PUT
HttpResponse response = httpClient.execute(httpPut);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
String result = convertStreamToString(is);
//9/10/2013: TODO-check for response codes in addition to these. Maybe, there is an error code being returned?
if (result.contains("0") || result.contains("1")) {
total += len;
temp = total * 100;
temp1 = temp / length;
//Updates object within async task.
mProgressDialog.setProgress((int) temp1);
}
else
{
/* Because this is controlled by an AsyncTask, we must bubble up that
* there has been a failure in the system if the user is unable to upload.
*
*/
return false;
}/**/
}
return true;
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
}
catch (ConnectTimeoutException e ){
//Took too long to connect to remote host
e.printStackTrace();
return false;
}
//Handled already by IOException.
catch (SocketTimeoutException e){
//Remote host didn’t respond in time
e.printStackTrace();
return false;
}/**/
//In case anything else is missing...
catch (Exception e) {
e.printStackTrace();
return false;
} finally {
try {
if (null != inputStream)
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
}
PHP Server Side code:
<?php
$CHUNK = 8192;
//$header_size=1024;
//7/16/2012: this will now be set to 0 by default, and only to 1 upon complete transmission of file.
$rslt=0;
$bytes_written=0;
//set error handler
set_error_handler("errorLogFunction");
try {
//Error handler test
//echo($test);
if (!($putData = fopen("php://input", "r")))
{
//throw new Exception ("Can't get PUT data.");
$log = new KLogger ( "putfile_php_log.txt" , KLogger::DEBUG );
// Do database work that throws an exception
$log->LogError("Can't get PUT data.");
// Print out some information
$log->LogInfo($errMsg);
}
else
{
$filedata_arr=explode("&",$filedata);
$mediadata_tmp=explode("=",$filedata_arr[0]);
$filetype=$mediadata_tmp[1];
$filename_tmp=explode("=",$filedata_arr[1]);
$filename=$filename_tmp[1];
$username_tmp=explode("=",$filedata_arr[2]);
$usr=$username_tmp[1];
$filesize_tmp=explode("=",$filedata_arr[3]);
$filesize=(int)$filesize_tmp[1];
$sha256sum_tmp=explode("=",$filedata_arr[4]);
$sha256sum=$sha256sum_tmp[1];
//echo "SHA read: " . $sha256sum . "<BR>";
$resume_tmp=explode("=",$filedata_arr[5]);
$resume=$resume_tmp[1];
//6/18/2013: Replace any spaces with underscores. For now, don't add date to filename.
$tmp2=ereg_replace(" ","_",$filename);
$targetFilename=$_SERVER['DOCUMENT_ROOT'] . '/received/'.$filetype.'/'.$usr."_".$tmp2;
//7/27/2012: Check if the user exists-if the user does not exist, do not allow the upload. Do this only once-if the file exists, don't run this check.
if (!file_exists($targetFilename))
{
if (checkIfUsernameExists($usr)==0)
{
$rslt=-9;
}
}
//Continue on only if file could be written
if ($rslt>=0)
{
// Open the file for writing
if ($resume==0)
{
if (!($fp = fopen($targetFilename, "w")))
{
//throw new Exception ("Can't write to tmp file");
//echo json_encode(-1);
//throw new Exception ("Can't get PUT data.");
$log = new KLogger ( "putfile_php_log.txt" , KLogger::DEBUG );
// Do database work that throws an exception
$log->LogError("Can't write to tmp file.");
// Print out some information
$log->LogInfo($errMsg);
$rslt=-1;
}
}
else
{
if (!($fp = fopen($targetFilename, "a")))
{
//throw new Exception ("Can't write to tmp file");
//throw new Exception ("Can't get PUT data.");
$log = new KLogger ( "putfile_php_log.txt" , KLogger::DEBUG );
// Do database work that throws an exception
$log->LogError("Can't append to tmp file.");
// Print out some information
$log->LogInfo($errMsg);
//echo json_encode(-2);
$rslt=-2;
}
else
{
$bytes_written=filesize($targetFilename);
}
}
if ($rslt>=0)
{
// Read the data a chunk at a time and write to the file.
while ($data = fread($putData, $CHUNK))
{
$chunk_read = strlen($data);
if (($block_write = fwrite($fp, $data)) != $chunk_read)
{
//throw new Exception ("Can't write more to tmp file");
//throw new Exception ("Can't get PUT data.");
$log = new KLogger ( "putfile_php_log.txt" , KLogger::DEBUG );
// Do database work that throws an exception
$log->LogError("Can't write more to tmp file.");
// Print out some information
$log->LogInfo($errMsg);
//echo json_encode(-3);
$rslt=-3;
break;
}
$bytes_written += $block_write;
//7/2/2012: Commented out temporarily until resume upload feature supported.
//echo "<BR>" . $tot_write . " written.";
//echo $tot_write;
}
if ( ! fclose($fp) )
{
//throw new Exception ("Can't close tmp file");
//echo json_encode(-4);
//throw new Exception ("Can't get PUT data.");
$log = new KLogger ( "putfile_php_log.txt" , KLogger::DEBUG );
// Do database work that throws an exception
$log->LogError("Can't close tmp file.");
// Print out some information
$log->LogInfo($errMsg);
$rslt=-4;
}
unset($putData);
// now the params can be used like any other variable
// see below after input has finished
// Check file length and SHA-256
//6/16/2012: no need to do filesize check anymore. Just do checksum.
/*if ($tot_write != $file_size)
{
throw new Exception ("Wrong file size");
//echo json_encode(-6);
$rslt=-6;
}*/
if (($rslt>=0) && ($bytes_written==$filesize))
{
//7/27/2012: Skipping checksum check because of iOS. Will consider adding another flag for checksum later.
/*$sha256_arr = explode(' ',exec("sha256sum $targetFilename"));
$sha256 = $sha256_arr[0];
if ($sha256 != $sha256sum)
{
//throw new Exception ("Wrong sha256");
//echo json_encode(-7);
$rslt=-7;
}
//if the checksums and filesizes match, return success.
else
{
$rslt=1;
}*/
//echo "<BR>Calculated SHA-256: " . $sha256 . "<BR>";
//echo "Read in SHA-256: " . $sha256sum . "<BR>";
$rslt=1;
}
//If the filesize and checksum match, send the messages indicating success.
}
}
}//if (put data)
}//try
catch (Exception $e)
{
//var_dump($e->getMessage());
//echo json_encode(-5);
$rslt=-5;
}
echo json_encode($rslt);
?>

Categories