Android Question upload file With php

Spinter

Active Member
Licensed User
I'm sorry my english with google translate
I need help. I would like to upload a file or an image with the php page on the webserver ?

I found and tried many posts but nothing that would lead me to solve. Can you help me?
 

Spinter

Active Member
Licensed User
thanks erel I've seen many posts for your feedback!
I tried but I did not get a result.
There are few examples with php I'm not able!
There is none who can help me?
 

lemonisdead

Well-Known Member
Licensed User
Hello Spinter,
Please, is it a problem about PHP or with B4A ? What don't you know how to do ?

Ciao Spinter,
Per favore, è un problema di PHP o con B4A? Quello che non sai come fare?
 

Spinter

Active Member
Licensed User
Grazie!
Scusa me sei italiano?
My post italian forum
http://www.basic4ppc.com/android/forum/threads/upload-file-con-php.37509/

Per sincerità avrei bisogno di un esempio completo!sia B4A che php!
Ho usato questo tipo di inserimento dati ma non vorrei usare base64.
Vorrei riuscire ad usare il multirepart request per inviare più file.

Traslated by Google!
For sincerity I would need a complete example! B4A is that php!
I have used this type of data entry but I would not use base64.
I would like to be able to use the multirepart request to send multiple files.

B4X:
--

Dim linkdb As String
linkdb="http://www.test.net/B4A.php"
Dim su As StringUtils
Dim out1 As OutputStream
out1.InitializeToBytesArray(100) 'size not really important
File.Copy2( File.OpenInput(File.DirRootExternal,"1.jpg"), out1)	 
job_camera_1.PostString(linkdb, su.EncodeBase64(out1.ToBytesArray))
out1.Close

<?php
    $base = file_get_contents("php://input");
    $binary=base64_decode($base);
    header('Content-Type: bitmap; charset=utf-8');
    $file = fopen('images/test_image.jpg', 'wb');
    fwrite($file, $binary);
    fclose($file);
    print json_encode('Image Upload Complete');
?>
 

DonManfred

Expert
Licensed User
Have a look at this example it uses erels multipartpost.bas. It uploads two files to a phpscript. On phpside the uploads are written to uploads-folder

Edit 29. August 2015:
I´ve added a new version of the example. This example uses the new okHTTP-Library.
Please note that i need to change the module multipartpost.bas to be compatible with the new okHTTP
 

Attachments

Last edited:

Spinter

Active Member
Licensed User
Return me this error

error: <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">


<html><head>
<title>501 Method Not Implemented</title>
</head><body>
<h1>Method Not Implemented</h1>
<p>GET to /B4A1.php not supported.<br />
</p>
<p>Additionally, a 404 Not Found
error was encountered while trying to use an ErrorDocument to handle the request.</p>
<hr>
<address>Apache Server at www.test.net Port 80</address>
</body></html>
501
 

Spinter

Active Member
Licensed User
I use a webhost on hostmoster.com
Maybe I have to configure anything?
I do not know much about php you can help me.
 

DonManfred

Expert
Licensed User
i dont know. i dont know this hoster and their possibilities at a webhosting...

Did you have PHP available on it? If yes, did you get any output from the multipartpost.php php-script when calling directly from a browser on your pc?

maybe you can post your app here. Export to zip
Also post the php-script you are using.... i can try it on my webspace then
 

DonManfred

Expert
Licensed User
@Spinter Please change the MultiPartPost.php! If you want to use it, it is incomplete for you and may output errors

Open PHP in Texteditor. On line 3 you´´ll find

PHP:
include('kernel.php');
PLEASE REMOVE THIS LINE! The script kernel.php is not part of this example and is not needed here.

Remark: I have updated the file multipartpost_phpside.zip in my post with the example.

That could be a solution for your errors. Maybe "include" is not allowed ("501 Method Not Implemented") AND the file kernel.php does not exists cause it was not part of the zip. Better to remove this line :)

Sorry, i did not recognized this line cause it is a standard-part of all php-projects i have made. So i overread them ;-)
(In kernel the database is initialized for example)

I forgot to remove this line before uploading it here. Sorry

It may fix your problem but if not you should check your php-config at your webhoster as posted from the dead lemon :D
 

Spinter

Active Member
Licensed User
i dont know. i dont know this hoster and their possibilities at a webhosting...

Did you have PHP available on it? If yes, did you get any output from the multipartpost.php php-script when calling directly from a browser on your pc?

maybe you can post your app here. Export to zip
Also post the php-script you are using.... i can try it on my webspace then
I am trying your example without modification to test if it works!

You have to configure your Php environment : https://my.hostmonster.com/cgi/help/128
And take a look at : https://my.hostmonster.com/cgi/help/110
I had read but my problem is that I do not know what I have to add!




include('kernel.php');

I had already removed it I knew that I needed!

thank you very much but I can not figure out the problem of the web server!
 

Spinter

Active Member
Licensed User
Code said:
<?php
if (!empty($_FILES['uploaded_file']))
{
move_uploaded_file($_FILES['uploaded_file']['tmp_name'],
"../../Control/Upload/".$_FILES['uploaded_file']['name']);

echo "<h2><u>File information</u></h2>";
echo "<b>Name:</b> ", $_FILES['uploaded_file']['name'], "<br />";
echo "<b>Type (MIME):</b> ", $_FILES['uploaded_file']['type'], "<br />";
echo "<b>Size (bytes):</b> ", $_FILES['uploaded_file']['size'], "<br />";
echo "<b>Location:</b> ", $_FILES['uploaded_file']['tmp_name'], "<br />";
echo "<b>Error Code:</b> ", $_FILES['uploaded_file']['error'];
}
else
{
echo "<form enctype='multipart/form-data' action='http://www.FAKESITE.com/php/Upload/index.php' method='post'> <br />";
echo "<input type='hidden' name='MAX_FILE_SIZE' value='' /> <br />";
echo "Choose a file to upload: <input type='file' name='uploaded_file' />";
echo "<input type='submit' value='Upload' /> <br />";
echo "</form>";
}
?>
Code said:
Dim filepath As String = IO.Path.Combine(Application.StartupPath, "filename.ext")
Dim url As String = "http://www.FAKESITE.com/php/Upload/index.php"

Dim boundary As String = IO.Path.GetRandomFileName
Dim header As New System.Text.StringBuilder()
header.AppendLine("--" & boundary)
header.Append("Content-Disposition: form-data; name=""uploaded_file"";")
header.AppendFormat("filename=""{0}""", IO.Path.GetFileName(filepath))
header.AppendLine()
header.AppendLine("Content-Type: application/octet-stream")
header.AppendLine()

Dim headerbytes() As Byte = System.Text.Encoding.UTF8.GetBytes(header.ToString)
Dim endboundarybytes() As Byte = System.Text.Encoding.ASCII.GetBytes(vbNewLine & "--" & boundary & "--" & vbNewLine)

Dim req As Net.HttpWebRequest = Net.HttpWebRequest.Create(url)
req.ContentType = "multipart/form-data; boundary=" & boundary
req.ContentLength = headerbytes.Length + New IO.FileInfo(filepath).Length + endboundarybytes.Length
req.Method = "POST"

Dim s As IO.Stream = req.GetRequestStream
s.Write(headerbytes, 0, headerbytes.Length)
Dim filebytes() As Byte = My.Computer.FileSystem.ReadAllBytes(filepath)
s.Write(filebytes, 0, filebytes.Length)
s.Write(endboundarybytes, 0, endboundarybytes.Length)
s.Close()





http://www.vbdotnetforums.com/net-sockets/25413-httpwebrequest-php-upload.html

As an experiment I tried a code in vb2010 and I tried it and it works perfectly!

So I think that the server-side function right?
 

DonManfred

Expert
Licensed User
For THIS php-Code

<?php
if (!empty($_FILES['uploaded_file']))
{
move_uploaded_file($_FILES['uploaded_file']['tmp_name'],
"../../Control/Upload/".$_FILES['uploaded_file']['name']);

echo "<h2><u>File information</u></h2>";
echo "<b>Name:</b> ", $_FILES['uploaded_file']['name'], "<br />";
echo "<b>Type (MIME):</b> ", $_FILES['uploaded_file']['type'], "<br />";
echo "<b>Size (bytes):</b> ", $_FILES['uploaded_file']['size'], "<br />";
echo "<b>Location:</b> ", $_FILES['uploaded_file']['tmp_name'], "<br />";
echo "<b>Error Code:</b> ", $_FILES['uploaded_file']['error'];
}
?>
You have to change things in APP-Code (you said you´re using it unchanged)

Dim files As List
files.Initialize
Dim fd As FileData
fd.Initialize
fd.Dir = File.DirAssets
fd.FileName = "snap1.png"
fd.KeyName = "uploaded_file" ' <--- THIS is what you check in php-file with if (!empty($_FILES['uploaded_file']))
fd.ContentType = "application/octet-stream"
files.Add(fd)
 

Spinter

Active Member
Licensed User
I tried it with your latest code I always generates the same error!


I tried this code with Eclipse, and it works! I can not understand where is the error in B4A!

Code said:
public void doFileUpload(String test_op){
HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
String exsistingFileName = test_op;

//String exsistingFileName = "/sdcard/1.jpg";
// Is this the place are you doing something wrong.
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";

int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
String responseFromServer = "";
String urlString = "http://www.myweb.net/upload_file.php";

try
{
//------------------ CLIENT REQUEST
Log.e("MediaPlayer","Inside second Method");
FileInputStream fileInputStream = new FileInputStream(new File(exsistingFileName) );

// open a URL connection to the Servlet
URL url = new URL(urlString);

// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();

// Allow Inputs
conn.setDoInput(true);

// Allow Outputs
conn.setDoOutput(true);

// Don't use a cached copy.
conn.setUseCaches(false);

// Use a post method.
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);

dos = new DataOutputStream( conn.getOutputStream() );
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
+ exsistingFileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
Log.e("MediaPlayer","Headers are written");

// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];

// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);

while (bytesRead > 0){
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}

// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

// close streams
Log.e("MediaPlayer","File is written");
fileInputStream.close();
dos.flush();
dos.close();

}

catch (MalformedURLException ex)

{

Log.e("MediaPlayer", "error: " + ex.getMessage(), ex);

}



catch (IOException ioe)

{

Log.e("MediaPlayer", "error: " + ioe.getMessage(), ioe);

}

//------------------ read the SERVER RESPONSE
try {
inStream = new DataInputStream ( conn.getInputStream() );
String str;

while (( str = inStream.readLine()) != null)
{
Log.e("MediaPlayer","Server Response"+str);
}

inStream.close();
}

catch (IOException ioex){
Log.e("MediaPlayer", "error: " + ioex.getMessage(), ioex);
}
}
 

Douglas Farias

Expert
Licensed User
DonManfred

how can i get only a note1 value?

if (isset($_REQUEST['note1'])){
$note1=trim($_REQUEST['note1']);
foreach($_REQUEST as $name => $value){
mkdir('naoenviadas/'.$value);
}
} else {
$iddapessoa="";
}

i m trying make this this get the value abc ok and make a dir in naoenviadas/abc

but make anothers folders
cde and upload

how can i get only the note1 value to make a dir?


updated
i try this too but dont work =(
$codigo = $_GET['note1'];
 
Last edited:
Top