I am developing a android app. In this app need to upload image to imageShack site using their api.
Here "sourceFileUri" is image file path which come from sdcard of the device.It shows Outh or dev Key is invalid.. Please can anyone help me to find out the error. Advanced Thanks.
private void goForUpload(final String sourceFileUri)
{
if (!SharedPreferencesHelper.isOnline(con))
{
return;
}
pDialog = ProgressDialog.show(this, "Please wait...", "Loading...",false, false);
final Thread d = new Thread(new Runnable()
{
#Override
public void run() {
String upLoadServerUri = " http://www.imageshack.us/upload_api.php";
String fileName = sourceFileUri;
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);
Log.w("file name are...", "" + sourceFile);
if (!sourceFile.isFile()) {
Log.e("uploadFile", "Source File Does not exist");
}
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);
// ///////////////////////////////////////////////////////////////////
//for image
dos.writeBytes("Content-Disposition: form-data; name=\"fileupload\";filename=\""+ fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"key\""+ lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes("289DGHSTbbfb01094c0017d23e96fe1edecda161");
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
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();
InputStream servere = conn.getInputStream();
String uyy = HttpRequest.GetText(servere);
System.out.print(uyy);
Log.w("uyy", "" + uyy);
Log.i("uploadFile", "HTTP Response is : "+ serverResponseMessage + ": " + serverResponseCode);
if (serverResponseCode == 200)
{
runOnUiThread(new Runnable()
{
public void run()
{
Toast.makeText(MainActivity.this,"File Upload Complete.",Toast.LENGTH_SHORT).show();
}
});
}
// close the streams //
fileInputStream.close();
dos.flush();
dos.close();
// Log.w("url", ""+url);
// final String url =
// "http://www.imageshack.us/upload_api.php?fileupload=http://www.libpng.org/pub/png/img_png/pnglogo-blk.jpg&url="+fos+"&optsize=100x100&rembar=yes&key=DHKNPRWYb185051e16c4545d8f26828d6fd3886c";
// final String url =
// "https://api.mobypicture.com/2.0/upload.json";//key=Az7IN9Qaxu3eZeK5/media=http://www.libpng.org/pub/png/img_png/pnglogo-blk.jpg/message=wasir";
//
// final String result = HttpRequest.GetText(HttpRequest
// .getInputStreamForGetRequest(url));
//
// try {
// if (parser.connect(con, result)) {
// Log.d("What is result :", result);
// }
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*
* update the GUI
*/
runOnUiThread(new Runnable() {
#Override
public void run() {
if (pDialog != null) {
pDialog.cancel();
}
}
});
}
});
d.start();
}
First Issue is the order you have your form-data parts:
dos.writeBytes("Content-Disposition: form-data; name=\"key\""+ lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes("xxxxxxxxxxxxxxxxxx");
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
//for image
dos.writeBytes("Content-Disposition: form-data; name=\"fileupload\";filename=\""+ fileName + "\"" + lineEnd);
dos.writeBytes("Content-Type: image/jpeg" + lineEnd);
dos.writeBytes("Content-Transfer-Encoding: binary" + lineEnd);
dos.writeBytes(lineEnd);
//dos.writeBytes(twoHyphens + boundary + lineEnd);
Second issue (when I tried) was that image type was invalid, so I added the content-type as seen above. And you didn't need the boundary before writing the file contents.
Related
i have some code to send some string parameters via POST method to server
my code is this:
public int uploadAghahi(aghahi AghahiToSend) {
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(AghahiToSend.imagePath);
if (!sourceFile.isFile()) {
prgDialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
}
});
return 0;
} else {
try {
JSONObject params = new JSONObject();
params.put("mainsubjectid", "1");
params.put("subsubjectid", "22");
params.put("stateid", "144");
params.put("cityid", "144");
params.put("onvan", "سیاسیباسیباشیباشسیباسیبا");
params.put("address", "سیاسیباسیباشیباشسیباسیبا");
params.put("phone", "سیاسیباسیباشیباشسیباسیبا");
params.put("email", "hseify69#gmail.com");
params.put("tozihat", "سیاسیباسیباشیباشسیباسیبا");
FileInputStream fileInputStream = new FileInputStream(
sourceFile);
URL url = new URL(ADDRESSsendAghahi);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept-Charset", "UTF-8");
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("uploaded_file", AghahiToSend.imagePath);
// conn.setRequestProperty("content-type",
// "application/json;charset=UTF-8");
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Type: text/plain; charset=UTF-8"
+ lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"obj\""
+ lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(params.toString());
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
// Json_Encoder encode=new Json_Encoder();
// call to encode method and assigning response data to variable
// 'data'
// String data=encode.encod_to_json();
// response of encoded data
// System.out.println(data);
// Adding Parameter filepath
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"filepath\""
+ lineEnd);
// dos.writeBytes("Content-Type: text/plain; charset=UTF-8"
// + lineEnd);
// dos.writeBytes("Content-Length: " + name.length() + lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(AghahiToSend.imagePath); // mobile_no is String
// variable
dos.writeBytes(lineEnd);
// Adding Parameter media file(audio,video and image)
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
+ AghahiToSend.imagePath + "\"" + 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);
serverResponseCode = conn.getResponseCode();
serverResponseMessage = conn.getResponseMessage();
InputStream is = conn.getInputStream();
BufferedReader reader = new BufferedReader(
new InputStreamReader(is));
String line = "";
while ((line = reader.readLine()) != null) {
result += line;
}
Toast.makeText(AddAghahiActivity.this, serverResponseMessage,
Toast.LENGTH_LONG).show();
if (serverResponseCode == 200) {
runOnUiThread(new Runnable() {
public void run() {
}
});
}
// close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
}
});
} catch (final Exception e) {
}
});
}
prgDialog.dismiss();
return serverResponseCode;
}
}
i have a problem and it is with encoding Strings.
some of my strings are in persian and when send to server they get changet to other characters like below:
,3ED3ED3~'3E'3ED4
or
*G1'F
How can i send params correctlly?
Find the appropriate encoding for the server, and encode your request with that encoding, and decode the response with that encoding too. For example, the code I did write yesterday on Python:
params = urllib.parse.urlencode({'tool': tool, 'input': full_text, 'token': token}).encode("UTF-8") # Encoding parameters
result = urllib.request.urlopen(api_url, params) # Making request
readed_result = result.read().decode("UTF-8") # Decoding response
The logic is the same in the Java too.
How to find appropriate encoding for server? Check http header for encoding.
For example:
public String uploadFile(String sourceFileUri) {
fileName = sourceFileUri;
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024;
File sourceFile = new File(sourceFileUri);
if (!sourceFile.isFile()) {
return "";
}
else
{
try {
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL urls = new URL(url_upload);
conn = (HttpURLConnection) urls.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setChunkedStreamingMode(1024);
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("fileName", fileName);
String cookie=AppController.getInstance().getPrefManger().getCookie();
Log.i("hello","cookie"+cookie);
conn.setRequestProperty("Cookie", cookie);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"albumId\"" + lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(selectedAlbumId); // mobile_no is String variable
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"caption\"" + lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(caption.getText().toString()); // mobile_no is String variable
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=files;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("hello", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
if(serverResponseCode == 200){
BufferedReader in=new BufferedReader(new InputStreamReader(conn.getInputStream()));
String temp;
while((temp=in.readLine())!=null)
{
Log.i("hello", "response is"+temp);
}
}
//close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
ex.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
}
});
Log.e("hello", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
e.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
}
});
Log.e("hello", "Exception : "+ e.getMessage(), e);
}
return String.valueOf(serverResponseCode);
} // End else block
}
This is my code which i am using to upload image or video to url.But when i upload files of different format the it fails to upload and unhandled type exception occurs.Please help How can i upload images and video of all type format
This is my code to send file to server over HTTP,
but i am trying to transfer using HTTPS i tried it for passing values using parameters it was working but i don't know how to code it with file stream,
can anybody help me with this i have ssl certificate
void Sending() {
String iFileName = "video.mp4";
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(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"title\""
+ lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(Title);
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"description\""
+ lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(Description);
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\""
+ iFileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
Log.e(Tag, "Headers are written");
// create a buffer of maximum size
int bytesAvailable = fileInputStream.available();
int maxBufferSize = 1024;
int bufferSize = Math.min(bytesAvailable, maxBufferSize);
byte[] buffer = new byte[bufferSize];
// read file and write it into form...
int bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
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();
} catch (MalformedURLException ex) {
Log.e(Tag, "URL error: " + ex.getMessage(), ex);
}
catch (IOException ioe) {
Log.e(Tag, "IO error: " + ioe.getMessage(), ioe);
}
}
I am building an app and at a certain point I need to upload an image to a server.
When I only put the image as a parameter, it all works perfectly but the problem is when I add the text, nothing happens. Here is my code
public int uploadFile(String sourceFileUri) {
String fileName = sourceFileUri;
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);
try {
// 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("uploaded_file", fileName);
conn.setRequestProperty("username", username);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
+ fileName + "\"" + lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"username\";filename=\""
+ username + "\"" + lineEnd);
dos.writeBytes("Content-Type: text/plain;charset=UTF-8" + 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);
if(serverResponseCode == 200){
runOnUiThread(new Runnable() {
public void run() {
String msg = "http://phpserver"+ture;
Toast.makeText(Friend.this, "Uploaded succesfully",
Toast.LENGTH_SHORT).show();
//new Post_test().execute();
}
});
}
//close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
dialog.dismiss();
ex.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(Friend.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() {
Toast.makeText(Friend.this, "Got Exception : see logcat ",
Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server Exception", "Exception : "
+ e.getMessage(), e);
}
dialog.dismiss();
return serverResponseCode;
}
What am I doing wrong?
When I remove :
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"username\";filename=\"" +
username + "\"" + lineEnd);
dos.writeBytes("Content-Type: text/plain;charset=UTF-8" + lineEnd);
the image gets uploaded, so the issue might come from how to add the text posts.
Any help?
This works for me!! I will adjust it to URLConnection in the future...
public int uploadFile(String sourceFileUri) {
String fileName=sourceFileUri;
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "------hellojosh";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File(fileName);
Log.e("joshtag", "Uploading: sourcefileURI, "+fileName);
if (!sourceFile.isFile()) {
Log.e("uploadFile", "Source File not exist :"+appSingleton.getInstance().photouri);//FullPath);
runOnUiThread(new Runnable() {
public void run() {
//messageText.setText("Source File not exist :"
}
});
return 0; //RETURN #1
}
else{
try{
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(upLoadServerUri);
Log.v("joshtag",url.toString());
// 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 s
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("user", user_id));
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);
Log.i("joshtag","->");
}
// 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().toString();
Log.i("joshtag", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode);
// ------------------ read the SERVER RESPONSE
DataInputStream inStream;
try {
inStream = new DataInputStream(conn.getInputStream());
String str;
while ((str = inStream.readLine()) != null) {
Log.e("joshtag", "SOF Server Response" + str);
}
inStream.close();
}
catch (IOException ioex) {
Log.e("joshtag", "SOF error: " + ioex.getMessage(), ioex);
}
//close the streams //
fileInputStream.close();
dos.flush();
dos.close();
if(serverResponseCode == 200){
//Do something
}//END IF Response code 200
dialog.dismiss();
}//END TRY - FILE READ
catch (MalformedURLException ex) {
ex.printStackTrace();
Log.e("joshtag", "UL error: " + ex.getMessage(), ex);
} //CATCH - URL Exception
catch (Exception e) {
e.printStackTrace();
Log.e("Upload file to server Exception", "Exception : "+ e.getMessage(), e);
} //
return serverResponseCode; //after try
}//END ELSE, if file exists.
}
After searching lots of resources i got nothing but when i tried to fetch text data from $_SERVER super global variable, i got all text data and $_FILE for getting image.
Here is the code given for android and php side both
package com.example.kingmash.Helper;
import android.content.Context;
import android.os.AsyncTask;
import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import com.example.kingmash.DAO.Profile_cover;
import com.example.kingmash.DAO.User_profile_cover;
import com.example.kingmash.MainActivity;
import com.example.kingmesh.R;
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.URL;
import java.util.ArrayList;
import java.util.HashMap;
import static com.example.kingmash.Helper.AllRequest.responseMessage;
public class UploadFileOnlyAsync extends AsyncTask<String, Void, String> {
String sourceFileUri, serverResponseMessage;
int serverResponseCode;
ProgressBar progressBar;
User_profile_cover upc;
int isdatainserted;
Context context;
public UploadFileOnlyAsync(Context context, String sourceFileUri, boolean requireprgressbar, User_profile_cover upc) {
this.sourceFileUri = sourceFileUri;
this.context = context;
progressBar = null;
this.upc = upc;
if (requireprgressbar) {
// progressBar = ((AppCompatActivity) context).findViewById(R.id.progressbar);
}
}
#Override
protected void onPreExecute() {
Log.d("on pre----", "on pre-----------");
if (progressBar != null) {
progressBar.setVisibility(View.GONE);
progressBar.setVisibility(View.VISIBLE);
}
}
#Override
protected void onProgressUpdate(Void... values) {
Log.d("On update-------------", "" + values[0]);
if (progressBar != null) {
progressBar.setProgress(Integer.parseInt(values[0].toString()));
}
}
#Override
protected String doInBackground(String... params) {
responseMessage = new Profile_cover(context).insert(upc, Routes.insertStepsURL);
if (responseMessage.get(0).equals("Inserted")) {
Log.d("key------insert fata", "" + isdatainserted);
try {
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()) {
try {
String upLoadServerUri = Routes.update_prfile_covrer_URL;
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(upLoadServerUri);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
// 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("user_id", "1");
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"profile\";filename=\""
+ sourceFileUri + "\"" + 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();
serverResponseMessage = conn
.getResponseMessage();
if (serverResponseCode == 200) {
// messageText.setText(msg);
//Toast.makeText(ctx, "File Upload Complete.",
// Toast.LENGTH_SHORT).show();
// recursiveDelete(mDirectory1);
}
// close the streams //
fileInputStream.close();
dos.flush();
dos.close();
String line;
ArrayList responseMessage = new ArrayList();
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = br.readLine()) != null) {
Log.d("line---", line);
responseMessage.add(line);
}
} catch (Exception e) {
// dialog.dismiss();
e.printStackTrace();
}
// dialog.dismiss();
} // End else block
} catch (Exception ex) {
// dialog.dismiss();
ex.printStackTrace();
}
}
Log.d("do in back-------------", "" + "Executed " + serverResponseMessage + "" + serverResponseCode + responseMessage);
return "Executed " + serverResponseMessage + "" + serverResponseCode + " " + responseMessage;
}
#Override
protected void onPostExecute(String result) {
if (progressBar != null) {
progressBar.setVisibility(View.GONE);
}
}
}
And here is the php code which is reading header from $_SERVER or getAllHeaders() function
<?php
session_start();
include '../Config/ConnectionObjectOriented.php';
include '../Config/DB.php';
$db = new DB($conn);
$user_id=$_SERVER["user_id"];
$info=$db->fileUploadWithTable($_FILES,"user_profile_cover",$user_id,"../img/user", "5m", "jpg,png");
echo $info[0];
echo $info[1];
// or you can check the detail by this code
foreach (getallheaders() as $name => $value) {
echo "$name: $value <br>";
}
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()) {
Log.e("uploadFile", "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);
// text to send
conn.setRequestProperty("uploaded_file", fileName);
String stringFieldName = "user_id";
conn.setRequestProperty("user_id", "999");
conn.setRequestProperty("sb_name", "testinggg");
Log.e("fileName", "fileName ======="+fileName);
dos = new DataOutputStream(conn.getOutputStream());
Log.e("uploadFile_uploadFile", "twoHyphens ="+twoHyphens +", boundary ="+boundary+", lineEnd ="+lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
Random r = new Random();
int rnd_filename = r.nextInt(999) + 1;
String strFileName="";
strFileName =rnd_filename +".png";
Log.e("strFileName", "strFileName ======="+strFileName);
// dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""+ fileName + "\"" + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""+ strFileName + "\"" + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"" + stringFieldName + "\""+ lineEnd);
dos.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available(); // create a buffer of maximum size
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);
if(serverResponseCode == 200){
runOnUiThread(new Runnable() {
public void run() {
tv.setText("File Upload Completed.");
Toast.makeText(UploadImageDemo.this, "File Upload Complete.", Toast.LENGTH_SHORT).show();
}
});
}
//close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
System.out.println("catch MalformedURLException ");
System.out.println("catch MalformedURLException ex ="+ex);
dialog.dismiss();
ex.printStackTrace();
Toast.makeText(UploadImageDemo.this, "MalformedURLException", Toast.LENGTH_SHORT).show();
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
System.out.println("catch Exception ");
System.out.println("catch Exception ex ="+e);
dialog.dismiss();
e.printStackTrace();
Toast.makeText(UploadImageDemo.this, "Exception : " + e.getMessage(), Toast.LENGTH_SHORT).show();
Log.e("Upload file to server Exception", "Exception : " + e.getMessage(), e);
}
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
System.out.println("RESULT Message: " + line);
}
rd.close();
} catch (IOException ioex) {
Log.e("Huzza", "error: " + ioex.getMessage(), ioex);
}
dialog.dismiss();
System.out.println("uploadFile END");
return serverResponseCode;
}
I want to upload image as well as text to the server.I am able to send the image to server but unable to send the text on the server.
this way i did it and working
//text with the image
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=text" + lineEnd); // GET text in PHP side
dos.writeBytes(lineEnd);
dos.writeBytes(UserPost); // mobile_no is String variable
dos.writeBytes(lineEnd);
//Username with image
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=usr" + lineEnd); // GET usr in PHP side
dos.writeBytes(lineEnd);
dos.writeBytes(name);
dos.writeBytes(lineEnd);