Encoding multipart form data in Android - java

And Python there's a pretty standard code for sending a multipart-form data, or rather, encoding it:
def encode_multipart_formdata(fields, files):
# fields is a sequence of (name, value) elements for regular form fields.
# files is a sequence of (name, filename, value) elements for data to be uploaded as files
# Return (content_type, body) ready for httplib.HTTP instance
BOUNDARY = '----------ThIs_Is_tHe_bouNdaRY_$'
CRLF = '\r\n'
L = []
for (key, value) in fields:
L.append('--' + BOUNDARY)
L.append('Content-Disposition: form-data; name="%s"' % key)
L.append('')
L.append(value)
for (key, filename, value) in files:
L.append('--' + BOUNDARY)
L.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename))
L.append('Content-Type: %s' % get_content_type(filename))
L.append('')
L.append(value)
L.append('--' + BOUNDARY + '--')
L.append('')
body = CRLF.join(L)
content_type = 'multipart/form-data; boundary=%s' % BOUNDARY
return content_type, body
I wonder, how can I do the same thing, encode multipart formdata, in Android?
I found a few solutions but none of them were supposed to do exactly the same thing as this one in python.

I checked if i used this code before, i can't really remember how exactly this works but here:
HttpURLConnection conn = null;
DataOutputStream dOut = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
URL url = new URL("http://shrimptalusan.hostei.com/usbong/build-upload.php");
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
setup the start of the multipart form:
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("utreeFile", utreeFilePath);
dOut = new DataOutputStream(conn.getOutputStream());
dOut.writeBytes(twoHyphens + boundary + lineEnd);
dOut.writeBytes("Content-Disposition: form-data; name=\"utreeFile\";filename=\"" + utreeFilePath + "\"" + lineEnd);
dOut.writeBytes(lineEnd);
bytesAvailable = utreeFileIn.available();
bufferSize = Math.min(bytesAvailable, maxBuffersize);
buffer = new byte[bufferSize];
bytesRead = utreeFileIn.read(buffer, 0, bufferSize);
Reading the file into a buffer:
while (bytesRead > 0) {
progress += bytesRead;
dOut.write(buffer, 0, bufferSize);
bytesAvailable = utreeFileIn.available();
publishProgress((int) ((progress * 100) / (utreeFile.length())));
bufferSize = Math.min(bytesAvailable, maxBuffersize);
buffer = new byte[bufferSize]; //TEST
bytesRead = utreeFileIn.read(buffer, 0, bufferSize);
}
Additional parameters to be included in the multipart entity:
//PARAMETER FIELD NAME
dOut.writeBytes(twoHyphens + boundary + lineEnd);
dOut.writeBytes("Content-Disposition: form-data; name=\"youtubelink\"" + lineEnd);
dOut.writeBytes(lineEnd);
dOut.writeBytes(youtubeLink); // mobile_no is String variable
dOut.writeBytes(lineEnd);
//PARAMETER END
Ending the multipart:
dOut.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
Sending the multipart via HTTP:
if (conn.getResponseCode() != HttpsURLConnection.HTTP_OK) {
utreeFileIn.close();
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
} else {
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
responseString += line;
}
}
Closing files and connections:
utreeFileIn.close();
dOut.flush();
dOut.close();
Hopefully it gives you a better idea. I don't think i used any external libraries. Here are my imports:
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;

Related

Invalid image POST request JAVA

I try to upload an image file with POST request and get the following response from server:
Notice: Undefined index: width in /home/api.webbankir.com/methods/photo.php on line 32
Notice: Undefined index: width in /home/api.webbankir.com/methods/photo.php on line 37
Notice: Undefined index: height in /home/api.webbankir.com/methods/photo.php on line 32
Notice: Undefined index: height in /home/api.webbankir.com/methods/photo.php on line 37
Fatal error: Uncaught exception 'Exception' with message 'Invalid image:
/home/api.webbankir.com/tmp/d9864480da25e440ff4d591498881e79.jpg' in
/home/api.webbankir.com/include/Simpleimage.php:1081
Stack trace:#0 /home/api.webbankir.com/include/Simpleimage.php(512): SimpleImage->get_meta_data()
#1/home/api.webbankir.com/methods/photo.php(97): SimpleImage-
>load('/home/api.webba...')
#2 /home/api.webbankir.com/methods/photo.php(411): Photo->load(Array)
#3 {main}thrown in /home/api.webbankir.com/include/Simpleimage.php on line 1081
Here is my JAVA code:
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1024 * 1024;
try {
connection = null;
URL url = new URL(url_link);
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("ENCTYPE", "multipart/form-data");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
connection.setRequestProperty("file", "img_webbankir.jpeg");
outputStream = new DataOutputStream( connection.getOutputStream() );
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"" + "img_webbankir.jpeg" +"\"" + lineEnd); /* img_webbankir.jpeg */
outputStream.writeBytes(lineEnd);
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
int dimension = Math.min(bitmap.getWidth(), bitmap.getHeight());
bitmap = ThumbnailUtils.extractThumbnail(bitmap, dimension, dimension);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
b = baos.toByteArray();
imageEncoded = Base64.encodeToString(b, Base64.DEFAULT);
outputStream.writeBytes(imageEncoded);
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
int serverResponseCode = connection.getResponseCode();
String serverResponseMessage = connection.getResponseMessage();
Log.e("log", "response code = " + serverResponseCode);
Log.e("log", "response message = " + serverResponseMessage);
outputStream.flush();
outputStream.close();
Log.e("log", "out put stream closed");
BufferedReader bufferedReader = new BufferedReader(new
InputStreamReader(connection.getInputStream()));
String line = "";
StringBuilder stringBuilder = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
bufferedReader.close();
response = stringBuilder.toString();
connection.disconnect();
} catch (IOException e) {
e.printStackTrace();
Log.e("Log", "error " + e);
}
I've tried the same request using OkHttp but got the same response...
I've also tried different ways of encoding the bitmap...
Will be grateful for help
Your client is in Java but error messages are from PHP. Therefore, it is server issue. Or you are not using server API properly. Are you integrating with 3-rd party, documented API or with your own PHP server?
If with your own server, you can debug the issue.
If we 3rd party API you should check their documentation if you are using API properly.
PS
for java rest client there are better, higher level tools than HttpURLConnection. Consider using https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/client/RestTemplate.html from spring.
https://github.com/square/okhttp or http://square.github.io/retrofit/ are also good choices. Your client code will be much shorter (2-5 lines, not 70), you will work on higher level of abstraction.
To reproduce the problem, please reproduce same post request with tools like Postman. https://www.getpostman.com/
That will rule out posibility of bug in your java code.

Missing bytes when uploading zip file with multipart/form-data using java

I'm having an issue with uploading a .zip file to a remote server in that some bytes are missing from the file after the upload. Upon redownloading the file, the .zip archive is unopenable, which leads me to believe that I need those bytes to perform the upload successfully.
I am using a multipart/form-data POST request to upload the file. The utility helper class I use to do this is given in the below code:
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
public class MultipartFormDataUtil {
private final String boundary;
private static final String lineReturn = "\r\n";
private HttpURLConnection conn;
private DataOutputStream dos;
int bytesRead, bytesAvail, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
List<String> response;
public MultipartFormDataUtil(String postUrl, LinkedHashMap<String, String> params, File file) throws IOException {
boundary = "=-=" + System.currentTimeMillis() + "=-=";
URL url = new URL(postUrl);
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
dos = new DataOutputStream(conn.getOutputStream());
for (String key : params.keySet()) {
addFormPart(key, params.get(key));
}
addFilePart(file);
finish();
}
private void addFormPart(String name, String value) throws IOException {
dos.writeBytes("--" + boundary + lineReturn);
dos.writeBytes("Content-Disposition: form-data; name=\"" + name + "\"" + lineReturn);
dos.writeBytes("Content-Type: text/plain" + lineReturn + lineReturn);
dos.writeBytes(value + lineReturn);
dos.flush();
}
private void addFilePart(File file) throws IOException {
FileInputStream fileInputStream = new FileInputStream(file);
dos.writeBytes("--" + boundary + lineReturn);
dos.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"" + lineReturn);
dos.writeBytes("Content-Type: " + URLConnection.guessContentTypeFromName(file.getName()) + lineReturn);
dos.writeBytes("Content-Transfer-Encoding: binary" + lineReturn + lineReturn);
bytesAvail = fileInputStream.available();
bufferSize = Math.min(bytesAvail, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvail = fileInputStream.available();
bufferSize = Math.min(bytesAvail, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
dos.flush();
dos.writeBytes(lineReturn);
dos.flush();
fileInputStream.close();
}
private void finish() throws IOException {
response = new ArrayList<String>();
dos.writeBytes("--" + boundary + "--" + lineReturn);
dos.flush();
dos.close();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
response.add(line);
}
reader.close();
conn.disconnect();
}
public List<String> getResponse() {
return response;
}
To give credit where credit is due, this utility is based off of examples from Peter's Notes and CodeJava.net. This util is called with the following code:
protected static void postFile(String url, LinkedHashMap<String, String> params, File file) throws Exception {
try {
MultipartFormDataUtil multipartRequest = new MultipartFormDataUtil(url, params, file);
List<String> response = multipartRequest.getResponse();
for (String line : response) {
System.out.println(line);
}
} catch (IOException ioe) {
log.warn("There was an error posting the file and form data", ioe);
}
}
The upload url in this case is to an Amazon S3 bucket, which passes it on to the destination system. It is at this final destination that I can see that the process that is supposed to be running on the .zip file has failed (note: the process is run by a Rails app and gives the error "Error identifying package type: can't dup NilClass"). Upon downloading the file, I see that the file size is 3,110,416 bytes instead of 3,110,466 bytes. I can no longer extract the archive to see what is in it; the mac archive utility responds with "Error 2 - No such file or directory".
I lack the conceptual background in this area to get a feel for where in the process things may be going wrong. I am hoping that someone will be able to tell me that I made an error in the utility class, or let me know that something else is the problem.
Thank you for any insight you can provide, and let me know if I can post anything else that would be of help.
EDIT: Some additional information I gathered about different sizes of file uploads (in bytes):
Original----------Uploaded----------Difference
10,167,389______10,167,238______151
3,110,466_______3,110,416_______50
156,885_________156,885_________0
95,639,352______95,637,925______1,427
For the 3 files that had bytes missing following the upload, the % of total data lost was around (but not exactly) 0.0015% for each one, but not equal to each other.
Upon some further research, we found that the error did not have anything to do with the multipart/form-data utility as shown in this question. Instead, it had to do with our own file downloading client in here. We were not setting the FileTransfer client to download the file as binary, which is necessary for a .zip file.
Feel free to use the code included in the original question for your multipart/form-data purposes in java - it works great assuming there are no problems with your original file.

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:)

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

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.

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