image not upload to php server , no response from servre on android - android

i doing app for uploading image to php server from android and the php server return a url as response for the request. i checked no problem in php server side it works fine for iphone. but in android i cannot get response. i have checked the php server my image is not uploaded. i do not know what is the problem in the code and how to get response. Is there is any setting needed? my code :
public class upload extends Activity {
InputStream is;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
Bitmap bitmapOrg = BitmapFactory.decodeFile("/sdcard/imageq.png");
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bitmapOrg.compress(Bitmap.CompressFormat.PNG, 90, bao);
byte [] ba = bao.toByteArray();
String ba1=Base64.encodeBytes(ba);
ArrayList<NameValuePair> nameValuePairs = new
ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("image",ba1));
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://xxxxxxxxxx/xxxxxx/upload.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
Log.e("uri",""+httppost.getURI());
Log.e("response",""+response);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("is",""+is);
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
}
}
i get the above code from http://blog.sptechnolab.com/2011/03/09/android/android-upload-image-to-server/
my log cat information:
05-11 10:09:39.488: ERROR/uri(1894): http://xxxxxxxxxx/xxxxxx/upload.php
05-11 10:09:39.488: ERROR/response(1894): org.apache.http.message.BasicHttpResponse#44f73610
05-11 10:09:39.495: ERROR/is(1894): org.apache.http.conn.EofSensorInputStream#44f1fc88
i print the getURI it returns what i give in the httppost = new HttpPost("...."). this is not real response from server. please help me.

package com.telubi.connectivity;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.util.Log;
import com.cipl.TennisApp.Login;
public class FileUploader {
private String Tag = "UPLOADER";
private String urlString;// = "YOUR_ONLINE_PHP";
HttpURLConnection conn;
String exsistingFileName;
public String result;
public String uploadImageData(String serverImageTag) {// Server image tag
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);
if (serverImageTag.equalsIgnoreCase("courtImage")) {
dos.writeBytes("Content-Disposition: post-data; name=courtImage[];filename="
+ exsistingFileName + "" + lineEnd);
} else if (serverImageTag.equalsIgnoreCase("userImage")) {
dos.writeBytes("Content-Disposition: post-data; name=userImage[];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 necessary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
String serverResponseMessage = conn.getResponseMessage();
BufferedReader rd = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
// String serverResponseCode = conn.
// String serverResponseMessage = conn.getResponseMessage();
while ((result = rd.readLine()) != null) {
Log.v("result", "result " + result);
Login.fbResponse = result;
}
// close streams
Log.e(Tag, "File is written");
fileInputStream.close();
dos.flush();
dos.close();
rd.close();
} catch (MalformedURLException ex) {
Log.e(Tag, "error: " + ex.getMessage(), ex);
}
catch (IOException ioe) {
Log.e(Tag, "error: " + ioe.getMessage(), ioe);
}
// Parsing has finished.
return result;
}
public FileUploader(String existingFileName, String urlString) {
this.exsistingFileName = existingFileName;
this.urlString = urlString;
}
}
I am using this code to upload image from device to php server by post method in this code you find a FilsUploader constructor pass file name you want upload and destination url (PHP server Url) for uploading file .I hope this is help.

Related

Audio File Upload to a Live Server in android

While I try to run the below code it doesn't show any error . its logs "File Witten ". but the file is not uploaded in the server. while I try the same code in locally with PHP code is able to upload. plz help .thanks in advance
package com.example.file_upload_demo;
import android.os.Handler;
import android.os.Message;enter code here
import android.util.Log;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class FileUploadUtility {
static String SERVER_PATH = "example.com";
enter code here
public static void doFileUpload(final String selectedPath, final Handler handler) {
//
new Thread(new Runnable() {
#Override
public void run() {`enter code here`
HttpsTrustManager.allowAllSSL();
HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
String lineEnd = "rn";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
String responseFromServer = "";
try {
//------------------ CLIENT REQUEST
FileInputStream fileInputStream = new FileInputStream(new File(selectedPath));
// open a URL connection to the Servlet
URL url = new URL(SERVER_PATH);
// 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", "application/json;charset=" + boundary);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"mp3File\";filename=\""
+ selectedPath + "\"" + 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);
sendMessageBack(responseFromServer, 0, handler);
return;
} catch (IOException ioe) {
Log.e("Debug", "error: " + ioe.getMessage(), ioe);
sendMessageBack(responseFromServer, 0, handler);
return;
}
responseFromServer = processResponse(conn, responseFromServer);
sendMessageBack(responseFromServer, 1, handler);
}
}).start();
}
private static String processResponse(HttpURLConnection conn, String responseFromServer) {
DataInputStream inStream;
try {
inStream = new DataInputStream(conn.getInputStream());
String str;
while ((str = inStream.readLine()) != null) {
responseFromServer = str;
}
inStream.close();
} catch (IOException ioex) {
Log.e("Debug", "error: " + ioex.getMessage(), ioex);
}
return responseFromServer;
}
static void sendMessageBack(String responseFromServer, int success, Handler handler) {
Message message = new Message();
message.obj = responseFromServer;
message.arg1 = success;
handler.sendMessage(message);
}`enter code here`
}
Try this:
1) open manifests folder in you app
2) add
<uses-permission android:name="android.permission.INTERNET" />
3) add <uses-permission android:name="android.permission.MANAGE_DOCUMENTS" />

Send JSON and image with HttpURLConnection in android

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.

how to send file from sd card to http post?

i want to send file from our app to sever through http post method.
My code is looking like as fallows
HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
String existingFileName = Environment.getExternalStorageDirectory().getAbsolutePath()
+ "/TamTrack/TamTrackDetails.xml";
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
String responseFromServer = "";
String urlString = "http://192.158.1.7/Geo/myfilename";
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)
Log.v("info",".size."+bytesRead);
for(int n1=0;n1<bytesRead;n1++)
{
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
Log.v("info","File is written");
fileInputStream.close();
dos.flush();
dos.close();
}
catch (MalformedURLException ex)
{
Log.v("info", "error: " + ex.getMessage(), ex);
}
catch (IOException ioe)
{
Log.v("info", "error: " + ioe.getMessage(), ioe);
}
//------------------ read the SERVER RESPONSE
try {
inStream = new DataInputStream ( conn.getInputStream() );
String str;
while (( str = inStream.readLine()) != null)
{
Log.v("info","Server Response "+str);
}
inStream.close();
}
catch (IOException ioex)
{
Log.v("info", "error: " + ioex.getMessage(), ioex);
}
return null;
It is working fine.but empty file is created in server.
If any one know the solution ,please help me .
Thanks in advance.
Try this code. It is using a class "SimpleMultipartEntity" using which you can easily send the file.
I'd prefer using Apache Http commons, it is part of android. I think this is a much simpler and cleaner approach. You need to do something like this:
AndroidHttpClient client = AndroidHttpClient.newInstance("useragent string");
URI uri = "something";
File file = new File("/tmp/data");
HttpPost post = new HttpPost(uri);
post.setEntity(new FileEntity(file, "text/html"));
HttpResponse httpResponse = client.execute(post);
int statusCode = httpResponse.getStatusLine().getStatusCode();

uploading video from android device and post that video on server

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

trouble in upload data android

i need to upload audio file(or any File) in server. i have asp.net server and refer this code but as per my doubt it is code of PHP server uploading.but i need to do in asp.net. so what is the changes to apply ?
one more thing is url liook like this :: http://xyz/MRESC/images/CustomizeActivity/193/ so its not store in Database it store in directory
Update ::
package com.upload;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
public class HttpFileUploader extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
DataInputStream inputStream = null;
//String pathToOurFile = "/sdcard/audiometer/shanesh1599870.mp3";
String pathToOurFile = "http://www.deviantart.com/download/78789749/Gohan_Jr__by_android_1.jpg";
//String urlServer = "http://asd/MRESC/images/CustomizeActivity/193/";
upLoad2Server(pathToOurFile);
}
public static int upLoad2Server(String sourceFileUri) {
String upLoadServerUri = "http://xyz/MRESC/images/CustomizeActivity/193/";
// 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()) {
return 0;
}
int serverResponseCode = 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("Huzza", "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("Huzza", "RES Message: " + line);
}
rd.close();
} catch (IOException ioex) {
Log.e("Huzza", "error: " + ioex.getMessage(), ioex);
}
return serverResponseCode; // like 200 (Ok)
} // end upLoad2Server
}
Permission ::
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
To upload a file on server I don't think so for asp .net and PHP server have a different code on android.
Just check your server side script. For android both are treated as a server (either a asp .net or PHP).
I don't know PHP or asp .net but take a look at these examples,
How to upload a file using Java HttpClient library working with PHP - strange problem
HTTP Post multipart file upload in Java ME
Upload image using POST, php and Android
Java Swing File upload with Php on the server
http://www.tizag.com/phpT/fileupload.php
In these, there are some example for java swing or java ME but I think just use the logic for upload file from java and then take look at how they handle on server side with php script.

Categories

Resources