I am uploading an audio file to a server, which works perfectly when the file name is something like:
abcd.3gp.
The problem is that anytime I record and upload another file, since the name is constant it overwrites the existing file which is not what I want. I want to always have a new file. I also do not want to use random numbers or anything like that.
So what I am doing now is that I have a datetime format in which I have removed all - or / and : from it and I store it in a variable.
For example, if I have this date:
2014-06-23 10:16:23
I turn this into:
06232014_101623
and then I add some extra text to it to get something like this:
06232014_101623ABC.3gp
This is the format that I want it in.
The problem is that when I record, it works and saves it perfectly with this name but when it starts to upload, I get a File Not Found exception, even though the file exists and is there.
The moment I change the name to something like abcd.3gp I get no exception and it uploads.
This is the code for recording:
Date currentDateTimeString= new Date();
DateFormat sdf;
sdf = new SimpleDateFormat("MMddyyyy_hhmmss");
String strDate = sdf.format(currentDateTimeString);
mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
mFileName += "/"+ strDate+TNumber+".3gp";
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setOutputFile(mFileName);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
try {
mRecorder.prepare();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
mRecorder.start();
This is the code for uploading:
Date currentDateTimeString= new Date();
DateFormat sdf;
sdf = new SimpleDateFormat("MMddyyyy_hhmmss");
String strDate = sdf.format(currentDateTimeString);
// TODO Auto-generated method stub
HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
String existingFileName =
Environment.getExternalStorageDirectory().getAbsolutePath();
existingFileName+= "/"+ strDate+TNumber+".3gp";
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
String urlString = "http://10.15.15.149/androidphp/Uploadaudio.php";
try {
//------------------ CLIENT REQUEST
FileInputStream fileInputStream =
new FileInputStream(new File(existingFileName));
// 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=\"uploadedfile\";filename=\"" + existingFileName + "\"" + 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);
// close streams
Log.e("Debug", "File is written");
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
Log.e("Debug", "error: " + ex.getMessage(), ex);
} catch (IOException ioe) {
Log.e("Debug", "error: " + ioe.getMessage(), ioe);
}
//------------------ read the SERVER RESPONSE
try {
inStream = new DataInputStream(conn.getInputStream());
String str;
while ((str = inStream.readLine()) != null) {
Log.e("Debug", "Server Response " + str);
}
inStream.close();
} catch (IOException ioex) {
Log.e("Debug", "error: " + ioex.getMessage(), ioex);
}
return null;
}
Any clue or assistance would be appreciated very much. Thank you.
I have solved my problem.
The problem was with the variable declaration scope for the currentDateTimeString. So After recording the audio file, since it is a date and time , the time changes before it starts uploading. So it in that case it will always have a different datetime value attached to the rest of the string which is different from the one on saved.
So I change the scope of the variable and now it holds the same datetime value through out
Related
Hello I am working with android . I want to send a multi-part data to asp.net web api. I have a json data and multiple images.I used the following method to post data to api
public int uploadFile(Context context,ArrayList<String> sourceFileUri,String json,String url1) {
// Toast.makeText(this,"uploading...", Toast.LENGTH_SHORT).show();
StrictMode.ThreadPolicy policy = new
StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Log.i("uploadimage", "" + sourceFileUri.get(0));
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(android.os.Environment.getExternalStorageDirectory() + "/TrackonPro", sourceFileUri.get(0));
if (!sourceFile.isFile()) {
Log.i("uploadFile", "Source File not exist :" + sourceFileUri);
return 0;
}
else
{
// Toast.makeText(this,"found Path : "+imagePath , Toast.LENGTH_LONG).show();
try {
// Toast.makeText(this,"try....", Toast.LENGTH_LONG).show();
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(url1);
// 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);
// Toast.makeText(this,"url : "+ url, Toast.LENGTH_LONG).show();
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
// JSON STRING
dos.writeBytes("Content-Disposition: form-data; name=\"sanu\"");
dos.writeBytes(lineEnd);
dos.writeBytes(json);
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
Log.i("immmm11",""+dos);
// IMAGE
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename="+ sourceFileUri + "" + lineEnd);
dos.writeBytes(lineEnd);
Log.i("immmm22", "" + dos);
// 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) {
// Toast.makeText(this,": while", Toast.LENGTH_LONG).show();
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);
Log.i("immmm33", "" + dos);
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
Log.i("uploadFile", "HTTP Response is : "+ serverResponseMessage + ": " + serverResponseCode);
// Toast.makeText(getApplicationContext(), "HTTP Response is : "+ serverResponseMessage + ": " + serverResponseCode,
// Toast.LENGTH_SHORT).show();
if(serverResponseCode == 200){
// Toast.makeText(context, "File Upload Complete.",
// Toast.LENGTH_SHORT).show();
}
//close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
ex.printStackTrace();
// Toast.makeText(context, "MalformedURLException",
// Toast.LENGTH_SHORT).show();
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
e.printStackTrace();
// Toast.makeText(context, " Exception : try again ! ",
// Toast.LENGTH_SHORT).show();
// Log.i("Upload file to server Exception", "Exception : " + e.getMessage());
}
return serverResponseCode;
} // End else block
}
by using this I can able to get upload images to server.But text not received at server side. But http post request using Fidler app to web API get uploaded both images and text ? Is there any problem with this sending data. Please help me thanks in advance
UPDATE
now I got the error at server
System.IO.IOException: Error writing MIME multipart body part to output stream. ---> System.InvalidOperationException: The stream provider of type 'MultipartFormDataStreamProvider' threw an exception. ---> System.InvalidOperationException: Did not find required 'Content-Disposition' header field in MIME multipart body part.
at System.Net.Http.MultipartFormDataStreamProviderHelper.IsFileContent(HttpContent parent, HttpContentHeaders headers)
at System.Net.Http.MultipartFormDataStreamProvider.GetStream(HttpContent parent, HttpContentHeaders headers)
at System.Net.Http.MimeBodyPart.GetOutputStream()
--- End of inner exception stack trace ---
at System.Net.Http.MimeBodyPart.GetOutputStream()
at System.Net.Http.MimeBodyPart.<WriteSegment>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Net.Http.HttpContentMultipartExtensions.<MultipartReadAsync>d__8.MoveNext()
--- End of inner exception stack trace ---
at System.Net.Http.HttpContentMultipartExtensions.<MultipartReadAsync>d__8.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Net.Http.HttpContentMultipartExtensions.<ReadAsMultipartAsync>d__0`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
at WebApplication.Areas.Json.Controllers.TravelClaimsController.<PostFormData>d__2.MoveNext()
I've used this method to upload multipart request (binary data and text)
public class HttpClient {
....
where the methods are:
public void connectForMultipart() throws Exception {
con = (HttpURLConnection) ( new URL(url)).openConnection();
con.setRequestMethod("POST");
con.setDoInput(true);
con.setDoOutput(true);
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
con.connect();
os = con.getOutputStream();
}
and
public void addFormPart(String paramName, String value) throws Exception {
writeParamData(paramName, value);
}
private void writeParamData(String paramName, String value) throws Exception {
os.write( (delimiter + boundary + "\r\n").getBytes());
os.write( "Content-Type: text/plain\r\n".getBytes());
os.write( ("Content-Disposition: form-data; name=\"" + paramName + "\"\r\n").getBytes());;
os.write( ("\r\n" + value + "\r\n").getBytes());
}
where
private String delimiter = "--";
private String boundary = "SwA"+Long.toString(System.currentTimeMillis())+"SwA";
The binary data (the image or something like that)
public void addFilePart(String paramName, String fileName, byte[] data) throws Exception {
os.write( (delimiter + boundary + "\r\n").getBytes());
os.write( ("Content-Disposition: form-data; name=\"" + paramName + "\"; filename=\"" + fileName + "\"\r\n" ).getBytes());
os.write( ("Content-Type: application/octet-stream\r\n" ).getBytes());
os.write( ("Content-Transfer-Encoding: binary\r\n" ).getBytes());
os.write("\r\n".getBytes());
os.write(data);
os.write("\r\n".getBytes());
}
When you call the HttpClient you add the parts:
HttpClient client = new HttpClient(url);
client.connectForMultipart();
client.addFormPart("param1", param1);
client.addFormPart("param2", param2);
client.addFilePart("file", "logo.png", baos.toByteArray());
client.finishMultipart();
and
public void finishMultipart() throws Exception {
os.write( (delimiter + boundary + delimiter + "\r\n").getBytes());
}
Hope it helps you. To have more info give a look at my blog post
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:)
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.
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
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