Can Any one have sample/example code for uploading video from android through my android application and store that video on server side.
Thanks in advance..
Here is another example. Very similar but the biggest difference is this is a data class designed to allow other post variables with it also. For example you have a specific file store for different users and groups. You then would want to send that data with the video. This data class can actually be used for all post to your site. So the data class is
public class MultiPartData {
final String requestURL = "http://www.yoursite.com/some.php";
final String charset="UTF-8";
final String boundary="*******";
private static final String LINE_FEED = "\r\n";
private HttpURLConnection httpConn;
private DataOutputStream outputStream;
private PrintWriter writer;
//establishes connection
public MultiPartData() throws IOException {
URL url = new URL(requestURL);
httpConn = (HttpURLConnection) url.openConnection();
httpConn.setUseCaches(false);
httpConn.setChunkedStreamingMode(4096);
httpConn.setDoOutput(true); // indicates POST method
httpConn.setDoInput(true);
httpConn.setRequestMethod("POST");
httpConn.setRequestProperty("ENCTYPE", "multipart/form-data");
httpConn.setRequestProperty("Content-Type",
"multipart/form-data; boundary=\"" + boundary + "\"");
httpConn.setRequestProperty("Connection", "Keep-Alive");
outputStream = new DataOutputStream(httpConn.getOutputStream());
writer = new PrintWriter(new OutputStreamWriter(outputStream, charset),true);
}
//adds post variables to the header body
public void addFormField(String name, String value) {
writer.append("--" + boundary).append(LINE_FEED);
writer.append("Content-Disposition: form-data; name=\"").append(name).append("\"")
.append(LINE_FEED);
writer.append("Content-Type: text/plain; charset=" + charset).append(
LINE_FEED);
writer.append(LINE_FEED);
writer.append(value).append(LINE_FEED);
writer.flush();
}
//adds files to header body can be anytype of files
public void addFilePart(String fieldName, String filePath) throws IOException {
File uploadFile=new File(filePath);
String fileName = uploadFile.getName();
writer.append("--" + boundary).append(LINE_FEED);
writer.append("Content-Disposition:form-data; name=\"")
.append(fieldName).append("\"; filename=\"")
.append(fileName).append("\"")
.append(LINE_FEED);
writer.append("Content-Type: ").append(URLConnection.guessContentTypeFromName(fileName))
.append(LINE_FEED);
writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
writer.append(LINE_FEED);
writer.flush();
FileInputStream inputStream = new FileInputStream(uploadFile);
int maxBufferSize=2*1024*1024;
int bufferSize;
int bytesAvailable=inputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
byte[] buffer = new byte[bufferSize];
int bytesRead=inputStream.read(buffer);
do {
outputStream.write(buffer, 0, bytesRead);
bytesAvailable = inputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = inputStream.read(buffer, 0, bufferSize);
}while (bytesRead >0);
outputStream.flush();
inputStream.close();
writer.append(LINE_FEED);
writer.flush();
}
//adds header values to body
public void addHeaderField(String name, String value) {
writer.append(name).append(": ").append(value).append(LINE_FEED);
writer.flush();
}
//closing options you must use one of the options to close the connection
// finishString() gets results as a string
// finnishJOBJECT() gets results as an JSONObject
// finnishJARRAY() gets results as an JSONArray
// finnishNoResponse() closes connection with out looking for response
public String finishString() throws IOException {
String response = "";
writer.append(LINE_FEED).flush();
writer.append("--" + boundary + "--").append(LINE_FEED);
writer.close();
String line;
StringBuilder sb= new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8"));
while ((line=br.readLine()) != null) {
sb.append(line);
response =sb.toString();
}
br.close();
return response;
}
public JSONObject finnishJOBJECT() throws IOException, JSONException {
JSONObject response = null;
writer.append(LINE_FEED).flush();
writer.append("--" + boundary + "--").append(LINE_FEED);
writer.close();
String line;
StringBuilder sb= new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8"));
while ((line=br.readLine()) != null) {
sb.append(line);
response =new JSONObject(sb.toString());
}
br.close();
return response;
}
public JSONArray finnishJARRAY()throws IOException, JSONException {
JSONArray response = null;
writer.append(LINE_FEED).flush();
writer.append("--" + boundary + "--").append(LINE_FEED);
writer.close();
String line;
StringBuilder sb= new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8"));
while ((line=br.readLine()) != null) {
sb.append(line);
response =new JSONArray(sb.toString());
}
br.close();
return response;
}
public void finnishNoResponse(){
writer.append(LINE_FEED).flush();
writer.append("--" + boundary + "--").append(LINE_FEED);
writer.close();
}
}
An example AsyncTask to implement the data class would be.
public void storeVideoBackground(String filePath,String identifier,String vType,String vName, storeImage serverPath){
progress.show();
new storeVideoAsyncTask(filePath,identifier,vType,vName,serverPath).execute();
}
public class storeVideoAsyncTask extends AsyncTask<Void,Void,String>{
String filePath; //path of the file to be uploaded
String vType; //variable used on server
String vName; //variable used on server
String identifier; //variable used on server
storeImage serverPath; //interface used to get my response
MultiPartData upload; //declares the data class for posting
public storeVideoAsyncTask(String filePath,String identifier,String vType,String vName, storeImage serverPath){
this.filePath=filePath;
this.vName=vName;
this.vType=vType;
this.identifier=identifier;
this.serverPath=serverPath;
}
#Override
protected String doInBackground(Void... params) {
JSONObject result;
String sPath="";
try {
upload=new MultiPartData();
upload.addHeaderField("User-Agent", "Android-User");
upload.addHeaderField("Test-Header","Header-Value");
upload.addFormField("appAuth",auth); //an auth string compared on server
upload.addFormField("action","storeVideo");//added post variable
upload.addFormField("vName",vName);//added post variable
upload.addFormField("identifier",identifier);//added post variable
upload.addFormField("vType",vType);//added post variable
upload.addFilePart("video",filePath);//added file video is the reference on server side to retrieve the file
sPath=upload.finishString();//returned server path to be used later
} catch (IOException e) {
e.printStackTrace();
}
return sPath;
}
#Override
protected void onPostExecute(String servPath) {
super.onPostExecute(servPath);
progress.dismiss();
serverPath.done(servPath);
}
}
Now I like reusing my code so this is part of another class called ServerRequest. I pass the context into it for progress dialog and declare other values like my appAuth.
The file is retrieved like so. This is server side php you can use any script you like to interact with the post variables.
if(isset($_FILES['video']['error'])){
$path = //path to store video
$file_name = $_FILES['video']['name'];
$file_size = $_FILES['video']['size'];
$file_type = $_FILES['video']['type'];
$temp_name = $_FILES['video']['tmp_name'];
if(move_uploaded_file($temp_name, $path.'/'.$file_name)){
$response =$path.'/'.$file_name;
}
}
The post variables will be retrieved usual methods $data=$_POST['data'];
If this code isn't working for files it would then be the result of something on your server. probably the file size. most hosted servers have restrictions on post size upload file size etc. Some will let you override that in your .htaccess. To debug the issue add an echo under if(isset in on server side to echo out the error code and the php manual has great explanations of what they mean. If it reads 1 then try to override php.ini in the .htaccess with something like this inside
php_value post_max_size 30M
php_value upload_max_filesize 30M
public static int uploadtoServer(String sourceFileUri) {
String upLoadServerUri = "your remote server link";
// String [] string = sourceFileUri;
String fileName = sourceFileUri;
HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
String responseFromServer = "";
File sourceFile = new File(sourceFileUri);
if (!sourceFile.isFile()) {
Log.e("My App", "Source File Does not exist");
return 0;
}
try {
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(upLoadServerUri);
conn = (HttpURLConnection) url.openConnection(); // Open a HTTP connection to the URL
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("uploaded_file", fileName);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""+ fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available(); // create a buffer of maximum size
Log.i("My App", "Initial .available : " + bytesAvailable);
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("Upload file to server", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode);
// close streams
Log.i("Upload file to server", fileName + " File is written");
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
ex.printStackTrace();
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
e.printStackTrace();
}
//this block will give the response of upload link
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(conn
.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
Log.i("My App", "RES Message: " + line);
}
rd.close();
} catch (IOException ioex) {
Log.e("Huzza", "error: " + ioex.getMessage(), ioex);
}
return serverResponseCode; // like 200 (Ok)
} // end uploadtoServer
Related
I got a FileNotFoundException error.
Code:
File getpath=Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES);
String dir= getpath.getAbsolutePath();
Log.e("filename of dir",dir);
//"/storage/emulated/0/Movies/"
try {
FileInputStream fstrm = new FileInputStream(dir+filename);
VideoFileUploadNew hfu = new VideoFileUploadNew( ServerURL.VIDEO_UPLOAD, filename);
upflag = hfu.Send_Now(fstrm);
Log.e("filename of v up",filename);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
public class VideoFileUploadNew implements Runnable {
URL connectURL;
String responseString;
String Title;
String fileName;
String Description;
byte[ ] dataToServer;
FileInputStream fileInputStream = null;
public VideoFileUploadNew(String urlString, String file){
try{
connectURL = new URL(urlString);
fileName = file;
}catch(Exception ex){
Log.i("HttpFileUpload","URL Malformatted");
}
}
public Boolean Send_Now(FileInputStream fStream){
fileInputStream = fStream;
return Sending();
}
Boolean Sending(){
System.out.println("file Name is :"+fileName);
String iFileName = fileName;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
String Tag="fSnd";
try
{
Log.e(Tag,"Starting Http File Sending to URL");
// Open a HTTP connection to the URL
HttpURLConnection conn = (HttpURLConnection)connectURL.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("Content-Disposition: form-data; name=\"vfile\";filename=\"" + iFileName +"\"" + lineEnd);
dos.writeBytes(lineEnd);
Log.e(Tag,"Headers are written");
// create a buffer of maximum size
int bytesAvailable = fileInputStream.available();
int maxBufferSize =9024;
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);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable,maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0,bufferSize);
}
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// close streams
fileInputStream.close();
dos.flush();
Log.e(Tag,"File Sent, Response: "+String.valueOf(conn.getResponseCode()));
InputStream is = conn.getInputStream();
// retrieve the response from server
int ch;
StringBuffer b =new StringBuffer();
while( ( ch = is.read() ) != -1 ){ b.append( (char)ch ); }
String s=b.toString();
Log.i("Response",s);
dos.close();
if(String.valueOf(conn.getResponseCode()).equals("200"))
{
return true;
}else{
return false;
}
}
catch (MalformedURLException ex)
{
Log.e(Tag, "URL error: " + ex.getMessage(), ex);
}
catch (IOException ioe)
{
Log.e(Tag, "IO error: " + ioe.getMessage(), ioe);
}
return false;
}
#Override
public void run() {
}
}
Your question is still pretty vague, but one of the reasons this happens is- when you're fetching the relative URI of the File, but need the Absolute URI for the upload.
You can check out different FileUtil classes like this https://github.com/z0rawarr/AndroidUtilCode/blob/master/utilcode/src/main/java/com/blankj/utilcode/utils/FileUtils.java
Get the absolute path from the URI and use that to upload.
Also, do not forget to use the Debugger, and apply a breakpoint on uploadFile() to debug the URIs.
I need to upload a photo taken by the camera's cellphone to a REST API called IMAGGA. I found in the API's documentation the following Java code:
String apiKey = "",
apiSecret = "";
HttpResponse response = Unirest.post("https://api.imagga.com/v1/content")
.basicAuth(apiKey, apiSecret)
.field("image", new File("/path/to/image.jpg"))
.asJson();
JSONObject jsonResponse = response.getBody().getObject();
System.out.println(jsonResponse.toString());
This code gives me an identifier, so I can use it to get the json from a image tagging.
I can't get it done because I'm using HttpURLConnection and I have no idea how to do that.
The only thing that i'm having problems with is the uploading part:
.field("image", new File("/path/to/image.jpg"))
To post an image to Imagga, use the postImageToImagga method below.
To do:
Please insert your own Basic Authorization details in the code from the Imagga dashboard, see the following line in code: connection.setRequestProperty("Authorization", "<insert your own Authorization e.g. Basic YWNjX>");
public String postImageToImagga(String filepath) throws Exception {
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
InputStream inputStream = null;
String twoHyphens = "--";
String boundary = "*****"+Long.toString(System.currentTimeMillis())+"*****";
String lineEnd = "\r\n";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
String filefield = "image";
String[] q = filepath.split("/");
int idx = q.length - 1;
File file = new File(filepath);
FileInputStream fileInputStream = new FileInputStream(file);
URL url = new URL("https://api.imagga.com/v1/content");
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("User-Agent", "Android Multipart HTTP Client 1.0");
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary="+boundary);
connection.setRequestProperty("Authorization", "<insert your own Authorization e.g. Basic YWNjX>");
outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"" + filefield + "\"; filename=\"" + q[idx] +"\"" + lineEnd);
outputStream.writeBytes("Content-Type: image/jpeg" + lineEnd);
outputStream.writeBytes("Content-Transfer-Encoding: binary" + lineEnd);
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
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);
inputStream = connection.getInputStream();
int status = connection.getResponseCode();
if (status == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
inputStream.close();
connection.disconnect();
fileInputStream.close();
outputStream.flush();
outputStream.close();
return response.toString();
} else {
throw new Exception("Non ok response returned");
}
}
To call the above code on a non-UI thread, we can use AsyncTask:
public class PostImageToImaggaAsync extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
}
#Override
protected Void doInBackground(Void... params) {
try {
String response = postImageToImagga("/mnt/sdcard/Pictures/Stone.jpg");
Log.i("imagga", response);
} catch (Exception e) {
}
return null;
}
#Override
protected void onPostExecute(Void result) {
}
}
To call the above PostImageToImaggaAsync code:
PostImageToImaggaAsync postImageToImaggaAsync = new PostImageToImaggaAsync();
postImageToImaggaAsync.execute();
i'm trying to send some data to a server. The server is waiting a json and an image. I tried with every example that i found but i couldn't send the data. Actually i'm sending the json params with a PrintWriter object, but it doesn't accept the image. I need to use HttpURLConnection not with the apache library. This is my piece of code working:
HttpURLConnection connection = null;
PrintWriter output = null;
ByteArrayOutputStream stream = new ByteArrayOutputStream();
attachImage.compress(Bitmap.CompressFormat.PNG, 40, stream);
byte[] imageData = stream.toByteArray();
String imagebase64 = Base64.encodeToString(imageData, Base64.DEFAULT);
Log.d(tag, "POST to " + url);
try{
URL url = new URL(this.url);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestProperty(HTTP_CONTENT_TYPE, "application/json; charset=utf-8");
connection.setRequestProperty(HTTP_USER_AGENT, mUserAgent);
connection.setRequestProperty(HTTP_HEADER_ACCEPT, "application/json; charset=utf-8");
connection.connect();
output = new PrintWriter(connection.getOutputStream());
JSONObject jsonParam = new JSONObject();
jsonParam.put("oauth_token", params.get("oauth_token"));
jsonParam.put("rating", "1");
jsonParam.put("comments", "ASDASDASDASDASDASDAS");
Log.d(tag, jsonParam.toString());
output.print(jsonParam);
output.flush();
output.close();
Log.d(tag, connection.getResponseCode() + connection.getResponseMessage());
}catch(Exception e ){
}
When I try to send an image in json params, I receive an 500 internal error message.
Thanks!
Okay , as per my suggestion 2 ways to send image to server
use base 64 string
Direct upload to server
1.for base 64 go to below link
Android post Base64 String to PHP
2.for direct upload to server Please check below link
http://www.androidhive.info/2014/12/android-uploading-camera-image-video-to-server-with-progress-bar/
Happy coding !!
People! After a lot of day, i could upload an image to a server! I was reading this library, which is for a lot of uses. https://source.android.com/reference/com/android/tradefed/util/net/HttpMultipartPost.html
I downloaded the source code, and i took some clases to send an image. I send only bytes, which were encoded from ASCII. Thanks for the help!
Check this below code to send form data and zip file containing images or other any media files.
private class MultipartFormTask extends AsyncTask<String, Void, String> {
String getStringFromInputStream(HttpURLConnection conn) {
String strResponse = "";
try {
DataInputStream inStream = new DataInputStream(
conn.getInputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(
inStream));
String line;
while ((line = br.readLine()) != null) {
strResponse += line;
}
br.close();
inStream.close();
} catch (IOException ioex) {
Log.e("Debug", "error: " + ioex.getMessage(), ioex);
}
return strResponse;
}
void uploadJSONFeed(HttpURLConnection conn, DataOutputStream dos,
String lineEnd) {
String issue_details_key = "issue_details";
String issue_details_value = "Place your Jsondata HERE";
try {
dos.writeBytes("Content-Disposition: form-data; name=\""
+ issue_details_key + "\"" + lineEnd
+ "Content-Type: application/json" + lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(issue_details_value);
dos.writeBytes(lineEnd);
} catch (IOException ioe) {
Log.e("Debug", "error: " + ioe.getMessage(), ioe);
}
}
void uploadZipFile(HttpURLConnection conn, DataOutputStream dos,
String lineEnd) {
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
try {
InputStream is = null;
try {
is = getAssets().open("Test.zip");
} catch (IOException ioe) {
// TODO Auto-generated catch block
Log.e("Debug", "error: " + ioe.getMessage(), ioe);
}
String zip_file_name_key = "file_zip";
String upload_file_name = "test.zip";
dos.writeBytes("Content-Disposition: form-data; name=\""
+ zip_file_name_key + "\";filename=\""
+ upload_file_name + "\"" + lineEnd); // uploaded_file_name
// is the Name
// of the File
// to be
// uploaded
dos.writeBytes(lineEnd);
bytesAvailable = is.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = is.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = is.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = is.read(buffer, 0, bufferSize);
}
dos.writeBytes(lineEnd);
is.close();
} catch (IOException ioe) {
Log.e("Debug", "error: " + ioe.getMessage(), ioe);
}
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
String urlString = "http://www.example.org/api/file.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);
uploadJSONFeed(conn, dos, lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
uploadZipFile(conn, dos, lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
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
String strResponse = getStringFromInputStream(conn);
return strResponse;
}
#Override
protected void onPostExecute(String result) {
// might want to change "executed" for the returned string passed
// into onPostExecute() but that is upto you
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG)
.show();
Log.e("Result:", result);
}
}
you can upload large jsonstring using buffer please use bellow code .
HttpsURLConnection connection = null;
OutputStream os = null;
InputStream is = null;
InputStreamReader isr = null;
try {
connection = (HttpsURLConnection) url.openConnection();
SSLContext contextSSL = SSLContext.getInstance("TLS");
contextSSL.init(null, new TrustManager[]{new DefaultTrustManager()}, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(contextSSL.getSocketFactory());
MySSLFactory(context.getSocketFactory()));
HttpsURLConnection.setDefaultHostnameVerifier(new MyHostnameVerifier());
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setChunkedStreamingMode(0);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Authorization", auth);
connection.setConnectTimeout(timeoutMillis);
OutputStream os ;
if (input != null && !input.isEmpty()) {
os = connection.getOutputStream();
InputStream stream = new ByteArrayInputStream(input.getBytes(StandardCharsets.UTF_8));
BufferedInputStream bis = new BufferedInputStream(stream, 8 * 1024);
byte[] buffer = new byte[8192];
int availableByte = 0;
while ((availableByte = bis.read(buffer)) != -1) {
os.write(buffer, 0, availableByte);
os.flush();
}
}
int responseCode = connection.getResponseCode();
HTTP 500 error code means a server-side error occured.
This has nothing to do with your code.
The server is having a bug, not your code.
I have tried to post multiple file to web service. But, single file post working multiple file post not working.
Please help me any one. How to implement that feature.
I have tried the below code. Please check it.
String fileName = sourceFileUri;
String fileName1 = sourceFileUri1;
// fileName1 - how to post to web service
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(sourceFileUri);
if (!sourceFile.isFile()) {
dialog.dismiss();
Log.e("uploadFile", "Source File not exist :" + imagepath);
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("Source File not exist :" + imagepath);
}
});
return 0;
} else {
try {
// open a URL connection to the Servlet
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("uploaded_file[]", fileName);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file[]\";filename=\""
+ fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
FileInputStream fileInputStream = new FileInputStream(
sourceFile);
// 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();
InputStream is = conn.getInputStream();
// retrieve the response from server
int ch;
StringBuffer b = new StringBuffer();
while ((ch = is.read()) != -1) {
b.append((char) ch);
}
String s = b.toString();
Log.i("Response", s);
} catch (MalformedURLException ex) {
dialog.dismiss();
ex.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
messageText
.setText("MalformedURLException Exception : check script url.");
Toast.makeText(MainActivity.this,
"MalformedURLException", Toast.LENGTH_SHORT)
.show();
}
});
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
dialog.dismiss();
e.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("Got Exception : see logcat ");
Toast.makeText(MainActivity.this,
"Got Exception : see logcat ",
Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server Exception",
"Exception : " + e.getMessage(), e);
}
dialog.dismiss();
return serverResponseCode;
}
If you want to pass an array of FileBody, you can try it like,
reqEntity.addPart("file[]["+i+"]", bab);
This will generate params like
file=>[{"1" => "File" },{"2" => "File"}..]
Hope it clarifies your doubt.
I got solution. I have used like as below. It's working.
public void uploadFileNew(ArrayList<String>IMAGEPTHLIST, ArrayList<String>IMAGENAMELIST) {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(upLoadServerUri);
ByteArrayBody bab;
ByteArrayOutputStream bos;
Bitmap bm;
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
for(int i = 0 ; i< IMAGEPTHLIST.size() ; i++) {
bm = BitmapFactory.decodeFile(IMAGEPTHLIST.get(i));
bos = new ByteArrayOutputStream();
bm.compress(CompressFormat.PNG, 100, bos);
byte[] data = bos.toByteArray();
bab = new ByteArrayBody(data, IMAGENAMELIST.get(i));
reqEntity.addPart("file["+i+"]", bab);
}
reqEntity.addPart("cat_id", new StringBody("123"));
reqEntity.addPart("name", new StringBody("Android test"));
postRequest.setEntity(reqEntity);
HttpResponse response2 = httpClient.execute(postRequest);
BufferedReader reader = new BufferedReader(new InputStreamReader(response2.getEntity().getContent(), "UTF-8"));
String sResponse;
StringBuilder s = new StringBuilder();
while ((sResponse = reader.readLine()) != null) {
s = s.append(sResponse);
}
System.out.println("===="+s.toString());
} catch (Exception e) {
e.printStackTrace();
}
dialog.dismiss();
}
before I ever send data and images with success, but it was done with two different procedures
this is my code to send data
public class HTTPPostData extends AsyncTask {
#Override
protected String doInBackground(String... urls) {
String Result = "";
byte[] Bresult = null;
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(URL_TO_LOAD);
try {
List<NameValuePair> nameValuePairs = LPD;
post.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
HttpResponse response = client.execute(post);
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpURLConnection.HTTP_OK) {
Bresult = EntityUtils.toByteArray(response.getEntity());
Result = new String(Bresult, "UTF-8");
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (Exception e) {
}
return Result;
}
protected void onPostExecute(String result) {
// dismiss the dialog after the file was downloaded
if (!result.toString().trim().equals("")) {
RunProcedure.StrParam = result;
RunProcedure.run();
}
}
}
and this my code to transfer pic
public boolean TransferFileToHttp(String address_to_handle, String file_name) {
boolean result = false;
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
// DataInputStream inputStream = null;
String pathToOurFile = file_name;
String urlServer = address_to_handle;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
try {
FileInputStream fileInputStream = new FileInputStream(new File(
pathToOurFile));
URL url = new URL(urlServer);
connection = (HttpURLConnection) url.openConnection();
// Allow Inputs & Outputs
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
// Enable POST method
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=\"uploadedfile\";filename=\""
+ pathToOurFile + "\"" + 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)
int serverResponseCode = connection.getResponseCode();
String serverResponseMessage = connection.getResponseMessage();
fileInputStream.close();
outputStream.flush();
outputStream.close();
result = true;
} catch (Exception ex) {
// Exception handling
result = false;
}
return result;
}
how to joining transfer file procedure to post data procedure and retrieve string as a result?
It is absolutely possible to do so. However, you will have to perform some additional steps.
You will first have to convert the image to a base 64 string. Refer to this document
http://developer.android.com/reference/android/util/Base64.html
Now the string can be sent as regular json data.
On the server end, you will need a mechanism to convert back the base64 string to image. It is a trivial task though.
There are some disadvantages of this method such as huge size of json request and additional overhead of encoding/decoding.