Android upload many files / images at once to a servlet with parameters - java

This can be same and can be seen as duplicate since there are many questions about uploading an image. But I want to know how to upload MANY images at a time to a servlet.That said, if there are 6 images in SD card, all should be uploaded within one request,not one by one. Most of samples over the internet are regarding one image or one file. I want to know if images are stored in a ArrayList, how they can be uploaded ?
In Servlet
List<FileItem> multiparts = new ServletFileUpload(
new DiskFileItemFactory()).parseRequest(request);
for(FileItem item : multiparts){
if(!item.isFormField()){
String name = new File(item.getName()).getName();
item.write( new File(UPLOAD_DIRECTORY + File.separator + name));
}
}
This part works fine as I tested with normal JSP multiplart many images uploads.
In android for one image upload (took from another source):
FileInputStream fileInputStream = new FileInputStream(new File(exsistingFileName) );
URL url = new URL(urlString);
conn = (HttpURLConnection) url.openConnection();
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=\"uploadedfile\";filename=\"" + exsistingFileName +"\"" + lineEnd);
dos.writeBytes(lineEnd);
Log.e("MediaPlayer","Headers are written");
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
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);
}
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
tv.append(inputLine);
// close streams
Log.e("MediaPlayer","File is written");
fileInputStream.close();
dos.flush();
dos.close();
This uploads only one image. How this can be used to send many with one POST request.? any other sample code or tutorial please.

Related

Can't upload file from android app to wep api

I am trying to upload an image file from an android app using java to an aspnet webapi with no success. I always get a response code of 500. Below is the basic code for preparing the sending of data from my android app. This code works when calling a php script but not when I call a web api controller shown below.
FileInputStream fileInputStream = new FileInputStream(sourceFile);
url = new URL("http://www.myserver.com/webapi/api/fileupload/post/thisfile");
connection = (HttpURLConnection) url.openConnection();
// Allow Inputs & Outputs.
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
// Set HTTP method to POST.
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
outputStream = new DataOutputStream( connection.getOutputStream() );
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\"" + sourceFile +"\"" + lineEnd);
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// Read file
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0)
{
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
serverResponseCode = connection.getResponseCode();
Below is the basic web api controller code to do the file upload:
[HttpPost]
[AcceptVerbs("GET", "POST")]
public Task<HttpResponseMessage> Post()
{
// Check if the request contains multipart/form-data.
if (!Request.Content.IsMimeMultipartContent())
{
// return "Unsupported media type";
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
string root = "e:/web/myserver/htdocs/cemetery/pics/";
var provider = new MultipartFormDataStreamProvider(root);
return task;
}
I changed the code above to send back a string and it says that my request does not contain multipart/form-data. Below is my webapiconfig.cs file route for this controller.
config.Routes.MapHttpRoute(
name: "FileUploadApi",
routeTemplate: "api/{controller}/{action}/{name}",
defaults: new { action = "post", name = RouteParameter.Optional }
);
I appreciate any help in determining what is wrong with my code so I can upload a file from an android java app to a webapi controller.

HttpURLConnection and writing file WITH DATA

I'm trying to post a file and data to my server from an Android java script (to my php), it seems I'm pretty much there, but someone PLEASE help me, as I can't seem to format the name/value part (the FILE uploads perfect, but it doesn't send the name value :( )
JAVA:
try{
int serverResponseCode = 0;
final String upLoadServerUri = "http://myUrl/upload_file_functions.php";
String fileName = "/mnt/sdcard/myFile.dat";
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File("/mnt/sdcard/myFile.dat");
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(upLoadServerUri);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("file", fileName);
conn.setRequestProperty("gmail", names[0]);
conn.setRequestProperty("phn", phn);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\""
+ fileName + "\"" + lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
String data = URLEncoder.encode("gmail", "UTF-8") + "=" + URLEncoder.encode(names[0], "UTF-8");
dos.writeBytes(data);
dos.writeBytes(lineEnd);
// 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);
dos.writeBytes("Content-Disposition: form-data; name=\"" + names[0] + "\"" + lineEnd);
dos.writeBytes("Content-Type: text/plain"+lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(names[0]);
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
//*************************
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
if(serverResponseCode == 200){
// it worked !
}
//close the streams //
fileInputStream.close();
dos.flush();
dos.close();
}catch (Exception e){
}
It doesn't work, the FILE sends fine, but I can't get a freaking key/name to send ("gmail:"names[0]) I've also tried:
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("gmail", names[0]);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\""
+ fileName + "\"" + lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
DOESN'T WORK. I've tried:
dos.writeBytes("Content-Disposition: form-data; name=\"gmail\";filename=\""+ names[0] + "\"" + lineEnd);
Doesn't WORK! WTF! I've programmed for years in C++ and python, it's a simple thing! But I can't figure this out I need help, if you know how to do it PLEASE DO TELL because I've spent two days banging my head against the wall. I'm not lazy I spent 32+ f'n hours on this please I beg you..
What I WANT to happen: send the file for upload, along with the value (name=gmail value=names[0]; name=phn value=phn), so that the email is associated to the file on my server.
What IS happening: file is uploading fine, but data is not passed (the name/value pairs are not sent)
PHP:
<?php
set_time_limit(100);
//need to get email also (gmail address of user)
//************************************************
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Stored in: " . $_FILES["file"]["tmp_name"];
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
}
}
function Three(){
$to = 'me#email.com';
$subject = $_POST['phn'] . " " . $_POST['gmail'];
$bound_text = "file";
$bound = "--".$bound_text."\r\n";
$bound_last = "--".$bound_text."--\r\n";
$headers = "From: me#email.com\r\n";
$headers .= "MIME-Version: 1.0\r\n"
."Content-Type: multipart/mixed; boundary=\"$bound_text\"";
$message .= "If you can see this MIME than your client doesn't accept MIME types!\r\n"
.$bound;
$message .= "Content-Type: text/html; charset=\"iso-8859-1\"\r\n"
."Content-Transfer-Encoding: 7bit\r\n\r\n"
."hey my <b>good</b> friend here is a picture of regal beagle\r\n"
.$bound;
$file = file_get_contents("http://myURL/upload/myFile.dat");
$message .= "Content-Type: image/jpg; name=\"myFile.dat\"\r\n"
."Content-Transfer-Encoding: base64\r\n"
."Content-disposition: attachment; file=\"myFile.dat"\r\n"
."\r\n"
.chunk_split(base64_encode($file))
.$bound_last;
#mail($to, $subject, $message, $headers);
//delete files
$fileArray=array($_FILES["file"]["name"],"myfile.dat","myfile.dat");
foreach($fileArray as $value){
if(file_exists($value)){
unlink($value);
}
}
chdir($old_path);
}
function runAll(){
One();
Two();
Three();
}
runAll();
$randx=null;
unset($randx);
?>
PLEASE HELP! The JAVA is not sending the name='gmail' value=names[0], nor the name='phn' value=phn ..
You should really read up on a few things: HTTP (and the distinction between request header fields and the post body), and the structure of a multipart/form-data post body.
This:
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("file", fileName);
conn.setRequestProperty("gmail", names[0]);
conn.setRequestProperty("phn", phn);
sends a few request headers, which is fine for Content-Type and such, but not necessarily for the data you're posting. Lose all but the Content-Type line.
This:
dos.writeBytes(twoHyphens + boundary + lineEnd);
is the right way to start a post field (or file), you should output this for every posted field.
This:
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
signals that all fields have been sent, you should send this as the very last line.
Either use something like Wireshark to see what your final request looks like (either side will do; the device doing the request or the server handling it), or log your request so you can inspect it, and see if it is perfect. It has to be nearly perfect for the webserver/php to process it correctly.
Well, I never figured out how to send a simple string parameter with the file upload, but my workaround was to simply append the filename of the upload file to INCLUDE the string I wanted to send:
#SuppressWarnings("deprecation")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
try{
Account[] accounts=AccountManager.get(this).getAccountsByType("com.google");
String myEmailid=accounts[0].toString(); Log.d("My email id that i want", myEmailid);
String[] names = new String[accounts.length];
for (int i = 0; i < names.length; i++) {
names[i] = accounts[i].name;
}
// THE DEVICE EMAIL ADDRESS WAS ONE OF THE DATA STRINGS I NEEDED TO SEND
File from = new File("/mnt/sdcard/","UPLOADFILE.DAT");
File to = new File("/mnt/sdcard/",names[0]+".BLOCK1."+"DATASTRING2"+".BLOCK2");
from.renameTo(to);
// DATASTRING2 is the SECOND piece of DATA I wanted to send
// SO YOU SEE I'M SIMPLY APPENDING THE UPLOAD FILE WITH THE DATA I WANT
// TO SEND WITH THE FILE, AND WHEN MY SERVER RECEIVES IT, I USE SOME SIMPLE
// PHP TO PARSE OUT WHATS BEFORE .BLOCK1. AND THEN .BLOCK2
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
try{
int serverResponseCode = 0;
final String upLoadServerUri = "http://MYURL/upload_file_functions.php";
String fileName = "/mnt/sdcard/"+names[0]+".BLOCK1."+"DATASTRING2"+".BLOCK2";
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File("/mnt/sdcard/"+names[0]+".BLOCK1."+"DATASTRING2"+".BLOCK2"");
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(upLoadServerUri);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
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=\"file\";filename=\""+ fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
// 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);
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
//close the streams //
fileInputStream.close();
dos.flush();
dos.close();
}catch (Exception e){
}
}catch (Exception e){
}
}
Thanks for the help! (THICK WITH SARCASM..) Seriously, I have to code in python, C++, java, PHP, on linux, Android, iPhone, Windows, MAC and Ubuntu... my work has me building Triple-Boot OS box's, building apps in Android and iPhone to support my business needs, and thus I must know PHP html and the like, needed to configure my own server because I needed email-notification services, so I needed to run my own email server (Exim on Ubuntu Server), and I've had to learn all this in the past 6 months.
Forgive me if my code's not pretty, but I don't have the luxury of time, as I'm going INSANE trying to keep up in the land of AI, Object recognition, and trying to make the rent (though I've learned enough to do so..)
DC:)

Uploading files to skydrive using java

As per Skydrive api(http://msdn.microsoft.com/en-us/library/live/hh826531.aspx#uploading_files), I am passing the content of the image in byte[] in the body of the post request.
the file creation happens on the skydrive server, but when i open it in skydrive it says "the file appers to be damaged or corrupted".
body of the post request
--A300x
Content-Disposition: form-data; name="file"; filename="menu-icon.png"
Content-Type: application/octet-stream
[B#11f3043
--A300x--
the response from the server.
<html>
<head>
<script type="text/javascript">
window.location = "http://localtesting.com/mywebapp-1.0-SNAPSHOT#state=000000004C0FA618&result=%7b%22id%22%3a%22file.918bb0fbaf82f760.918BB0FBAF82F760!139%22%2c%22name%22%3a%22menu-icon.png%22%2c%22source%22%3a%22https%3a%2f%2f1m61va.tuk.livefilestore.com%2fy2mhncDTiOhUVFZxp08gi3yAFhp7OQ2-UYuQhnC_Obpoo4q5tG6onLuJz2mLJkJh6lUW5l8Cq2KBxvrLRrZ0bk6V7xmfso47cJWAw1fKE8bFJw%2fmenu-icon.png%3fdownload%26psid%3d1%22%7d";
</script>
</head>
</html>
code for converting the image into byte[]
byte[] image=FileUtils.readFileToByteArray(physicalfile);
Any clue?
EDIT:
Following is the code snippet I use
I'm taking some parts from properties file.
env.properties
part1=--A300x\u000d\u000aContent-Disposition: form-data; name=\"file\"; filename=\"
part2=\"\u000d\u000aContent-Type: application/octet-stream\u000d\u000a\u000d\u000a
part3=\u000d\u000a--A300x--
java file
String part1=bundle.getString("part1");
String part2= fileName+bundle.getString("part2");
String part3=bundle.getString("part3");
byte[] imageByteArray=FileUtils.readFileToByteArray(physicalfile);
PostMethod postMethod= new PostMethod("https://apis.live.net/v5.0/"+folderPath+"/files?state="+getSkydriveClientId()+"&redirect_uri="+baseURL+"&access_token="+getAcessToken());
postMethod.setRequestHeader("Content-Type","multipart/form-data; boundary=A300x");
postMethod.setRequestBody(part1+part2+imageByteArray+part3);
HttpClient httpClient=new HttpClient();
httpClient.executeMethod(postMethod);
You appear to be calling toString() on your byte array - that's what's converting it to [B#11f3043. You haven't shown us any of the code you're using to make the request, but basically you need to avoid calling toString(). I don't know whether the API accepts a byte[], but you should at least try to find a method which takes one, as that would be appropriate for your content.
EDIT: Looking at the sample code, it appears you can pass in an InputStream to LiveConnectClient.uploadAsync - so just wrap your byte[] in a ByteArrayInputStream.
Got it working with the following code snippet,after trimming spaces in client id and baseURL.
String BOUNDARY_STRING="A300x";
String urlString="https://apis.live.net/v5.0/"+folderPath+"/files?state="+getSkydriveClientId()+"&redirect_uri="+baseURL+"&access_token="+getAcessToken();
URL connectURL = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) connectURL.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type","multipart/form-data; boundary=" + BOUNDARY_STRING);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestProperty("Connection", "Keep-Alive");
conn.connect();
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes("--" + BOUNDARY_STRING + "\r\n");
dos.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"" + fileName + "\"\r\n");
dos.writeBytes("Content-Type: application/octet-stream\r\n");
dos.writeBytes("\r\n");
File fileToUpload=Util.getFile(fileName);
FileInputStream fileInputStream = new FileInputStream(fileToUpload);
int fileSize = fileInputStream.available();
int maxBufferSize = 8192;
int bufferSize = Math.min(fileSize, maxBufferSize);
byte[] buffer = new byte[bufferSize];
int bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bytesRead);
int bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, buffer.length);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
fileInputStream.close();
dos.writeBytes("\r\n");
dos.writeBytes("--" + BOUNDARY_STRING + "--\r\n");
dos.flush();

HTTPURLConnection.getInputStream() Takes a very long time?

I'm uploading an image file using a HttpURLConnection which takes about 3 seconds for a 5MB file with all the headers, but the moment I open an InputStream with .getInputStream(), the method takes about 8+ seconds to return a stream with. Which is an issue because it seems the upload progress bar gives a bad UX if I have multiple images to upload, they have a considerable pause between each upload, so the progress bar just stops for a couple of seconds between uploads. I've done some googling but no one else seems to have an issue with it?
Normally I would assume the server is slow, but seeing as uploading only takes a couple of seconds, downloading the word 'success' or 'fail' shouldn't really be that much of an issue!
Heres some code! Am I setting anything up wrong initially?
Note: This is also within an AsyncTask
ByteArrayInputStream fileInputStream = null;
try {
fileInputStream = new ByteArrayInputStream(dObject.Data);
} catch (Exception e) {
e.printStackTrace();
}
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
String Tag="3rd";
try
{
//------------------ CLIENT RE QUEST
Log.e(Tag,"Inside second Method");
// Open a HTTP connection to the URL
URL url = new URL(_urlString);
//connectURL is a URL object
HttpURLConnection 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);
DataOutputStream dos = new DataOutputStream( conn.getOutputStream() );
dos.writeBytes(twoHyphens + boundary + lineEnd);
//dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + _fileLocation +"\"" + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\"" + _fileLocation +"\"" + lineEnd);
dos.writeBytes(lineEnd);
Log.e(Tag,"Headers are written");
// create a buffer of maximum size
int bytesAvailable = fileInputStream.available();
int maxBufferSize = 1024;
int bufferSize = Math.min(bytesAvailable, maxBufferSize);
byte[] buffer = new byte[bufferSize];
// read file and write it into form...
int bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
//int value = (int)(((float)((float)totalRead / (float) fileSize)) * 100);
totalRead += bytesRead;
//Publish the progress out to be displayed
publishProgress(totalRead);
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(Tag,"File is written");
fileInputStream.close();
dos.flush();
Log.e("TIME", "PRE GETINPUTSTREAM");
InputStream is = conn.getInputStream();
Log.e("TIME", "POST GETINPUTSTREAM");
// retrieve the response from server
int ch;
//Build the respose and log
StringBuilder b =new StringBuilder();
while( ( ch = is.read() ) != -1 ){
b.append( (char)ch );
}
String s=b.toString();
Log.i("Response",s);
dos.close();
return;
}
catch (MalformedURLException ex)
{
ErrorHandler.get().e("3");
}
catch (IOException ioe)
{
ErrorHandler.get().e("2");
}
Normally I would assume the server is slow, but seeing as uploading only takes a couple of seconds, downloading the word 'success' or 'fail' shouldn't really be that much of an issue!
I suspect that it really is that the server is slow or overloaded.
The server could be queueing the HTTP requests and only processing a small number at a time in parallel.
Or it could have a bottleneck in some database activity that is performed before the response containing the file is written to the response.
Or it could be generating the file on the fly into an in-memory buffer (slow) and then streaming (fast) from the buffer to the HTTP response.
Or other explanations like this ...
(It is also theoretically possible that there is something funny going on that slows up the delivery of the request to the server. I would think this was unlikely though.)
Have you tried downloading the same file using a web browser? Do you get the same behaviour there?
In my case I found that getInputStream looks slow because this method initialize the ssl handshake (on a https URL call). After the first call, others calls are OK

Android file uploader with server-side php

I've been looking for a solution to this for hours, but I can't find any.
Basically, I want to upload, from my android device, files to an http website. However, I have no clue whatsoever how to do this. I'm using java on the device, and I would like to use PHP on the server-side of things. I just want to upload the files, not do anything fancy with them on the server.
Can anyone provide code and/or a good link to what I need? I have little to no experience in this, and I am at a loss.
Thanks,
NS
PS. I have no experience in PHP coding.
Yeah, so I found the java-side of things. This works, so... yeah.
public class Uploader extends Activity {
private String Tag = "UPLOADER";
private String urlString = "YOUR_ONLINE_PHP";
HttpURLConnection conn;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String exsistingFileName = "/sdcard/uploader/data/testfile";
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
try {
// ------------------ CLIENT REQUEST
Log.e(Tag, "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);
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos
.writeBytes("Content-Disposition: post-data; name=uploadedfile;filename="
+ exsistingFileName + "" + lineEnd);
dos.writeBytes(lineEnd);
Log.e(Tag, "Headers are written");
// create a buffer of maximum size
int bytesAvailable = fileInputStream.available();
int maxBufferSize = 1000;
// int bufferSize = Math.min(bytesAvailable, maxBufferSize);
byte[] buffer = new byte[bytesAvailable];
// read file and write it into form...
int bytesRead = fileInputStream.read(buffer, 0, bytesAvailable);
while (bytesRead > 0) {
dos.write(buffer, 0, bytesAvailable);
bytesAvailable = fileInputStream.available();
bytesAvailable = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bytesAvailable);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// close streams
Log.e(Tag, "File is written");
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
Log.e(Tag, "error: " + ex.getMessage(), ex);
}
catch (IOException ioe) {
Log.e(Tag, "error: " + ioe.getMessage(), ioe);
}
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(conn
.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
Log.e("Dialoge Box", "Message: " + line);
}
rd.close();
} catch (IOException ioex) {
Log.e("MediaPlayer", "error: " + ioex.getMessage(), ioex);
}
}
}
If you want to upload files that is larger than 2MB you need to edit your PHP configuraton
; Maximum allowed size for uploaded files.
; http://php.net/upload-max-filesize
upload_max_filesize = 2M
Eg:
; Maximum allowed size for uploaded files.
; http://php.net/upload-max-filesize
upload_max_filesize = 10M
That would allow you to upload files up to 10MB of size
For the PHP side of things take a look at
move_uploaded_file and also the global $_FILES
http://php.net/manual/en/function.move-uploaded-file.php
http://php.net/manual/en/features.file-upload.php

Categories