I need to upload my file android device to server using webservice. But unfortunately Im getting error while doing it.Please help me to clear this error.
Here is my java code:
public class HttpFileUpload implements Runnable {
URL connectURL;
String responseString;
String Title;
String Description;
byte[ ] dataToServer;
FileInputStream fileInputStream = null;
HttpFileUpload(String urlString, String vTitle, String vDesc){
try{
connectURL = new URL(urlString);
Title= vTitle;
Description = vDesc;
}catch(Exception ex){
Log.i("HttpFileUpload","URL Malformatted");
}
}
void Send_Now(FileInputStream fStream){
fileInputStream = fStream;
Sending();
}
void Sending(){
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
String iFileName = "ovicam_temp_vid.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)
{
ioe.printStackTrace();
Log.e(Tag, "IO error: " + ioe.getMessage(), ioe);
}
}
#Override
public void run() {
// TODO Auto-generated method stub
}
}
LogCat:
java.io.FileNotFoundException: http:///****8*******8/*****
at com.android.okhttp.internal.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:210)
at arun.com.test.HttpFileUpload.Sending(HttpFileUpload.java:118)
at arun.com.test.HttpFileUpload.Send_Now(HttpFileUpload.java:36)
the average REST webservice won't return a response body on POST/PUT, just a response status. You'd like to determine it instead of the body.
Replace
InputStream response = conn.getInputStream();
by
int status = conn.getResponseCode();
All available status codes and their meaning are available in the HTTP spec, as linked before. The webservice itself should also come along with some documentation which overviews all status codes supported by the webservice and their special meaning, if any.
If the status starts with 4nn or 5nn, you'd like to use getErrorStream() instead to read the response body which may contain the error details.
InputStream error = con.getErrorStream();
Taken from this answer
Related
I am developing android application where user will upload video to server. I am new to android development so I cannot grasp the concept of uploading video. The thing I know is that I need to create an intent to ask user to choose the video and then convert it to uri file. I'm planning on using asynctask with httpurlconnection. Can anyone help me what to do with asynctask?
I think this will help you
upload video
public static int upLoad2Server(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("Huzza", "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("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
I am recording audio and trying to upload audio on soundcloud server.but its not working can someone please correct me where i am doing wrong.I have searched alot but nothing works for me.I am a beginer in java.I already wasted 1 day on solving this problem.
private class AsyncTaskRunner extends AsyncTask<String,Void,String> {
#Override
protected String doInBackground(String... params) {
doFileUpload();
return null;
}
}
private void doFileUpload(){
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 = "";
String urlString = "http://api.soundcloud.com/tracks";
try
{
//------------------ CLIENT REQUEST
FileInputStream fileInputStream = new FileInputStream(new File(AudioSavePathInDevice) );
// 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() );
//Adding oauth token
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"oauth_token\""+lineEnd+lineEnd+access_token+lineEnd);
// dos.writeBytes(lineEnd);
//Adding Track title
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"track[title]\""+lineEnd+lineEnd+contributor_name+lineEnd);
// dos.writeBytes(lineEnd);
//Track taglist
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"track[tag_list]\""+lineEnd+lineEnd+"Tagore Project"+lineEnd);
// dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"track[asset_data]\";filename=\"" + AudioSavePathInDevice + "\"" + lineEnd);
// dos.writeBytes(lineEnd);
//Add sharing
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"track[sharing]\""+lineEnd+lineEnd+sharing+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);
Toast.makeText(this, ex.getMessage(), Toast.LENGTH_SHORT).show();
}
catch (IOException ioe)
{
Log.e("Debug", "error: " + ioe.getMessage(), ioe);
Toast.makeText(this, ioe.getMessage(), Toast.LENGTH_SHORT).show();
}
//------------------ read the SERVER RESPONSE
// try {
// DataInputStream inStream = new DataInputStream ( conn.getInputStream() );
// String str;
// Log.e("Debug","Before while");
// while (( str = inStream.readLine()) != null)
// {
// Log.e("Debug","Server Response "+str);
// }
// inStream.close();
//
// }
try (InputStream is = conn.getInputStream()) {
BufferedReader lines = new BufferedReader(new InputStreamReader(is, "UTF-8"));
// if(is == null) {
// Log.e("Debug","Reponse null ");
// }
// if(lines == null) {
// Log.e("Debug","Reponse null ");
// }
// int count = 0;
while (true) {
Log.e("Debug","Server Response ");
String line = lines.readLine();
if (line == null) {
Log.e("Debug","Server Break");
break;
}
}
}
catch (IOException ioex){
Log.e("Debug", "error: " + ioex.getMessage(), ioex);
}
}
and calling Asynctask like below on onClicklistener.
new AsyncTaskRunner().execute();
I have used this code snippet to write an AsyncTask class that sends an image to a server. Here is a part of code in doInBackground method that is responsible for sending the image and a few arguments:
String fileName = params[3];
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(fileName);
if (!sourceFile.isFile()) {
Log.e("debug", "Source File not exist: " + fileName);
} else {
try {
/////////////////////////////////////////////////////////////////////////////
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(params[0]);
// 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("pic", fileName);
dos = new DataOutputStream(conn.getOutputStream());
//here I add some additional data
addFormField(dos,"idapp", params[1]);
addFormField(dos,"idlesson", params[2]);
addFormField(dos,"ip", params[4]);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"pic\";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);
String byteArray = "";
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
byteArray += buffer.toString();
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)
int serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
Log.i("debug", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
BufferedInputStream in;
try {
in = new BufferedInputStream(conn.getInputStream());
} catch (IOException e) {
String err = (e.getMessage() == null) ? "IOException in creating BufferedInputStream" : e.getMessage();
Log.e("debug", err);
return err;
}
try {
resultToDisplay = IOUtils.toString(in, "UTF-8");
//to [convert][1] byte stream to a string
} catch (IOException e) {
Log.e("debug", e.getMessage());
}
Log.i("debug", "result: " + resultToDisplay);
//close the streams //
//////////////////////////////////////
fileInputStream.close();
dos.flush();
dos.close();
//////////////////////////////////////
} catch (MalformedURLException ex) {
Log.e("debug", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
Log.e("debug", "error: " + e.getMessage(), e);
}
} // End else block
return resultToDisplay;
And here is how do I invoke it:
CallAPI c = new CallAPI();
c.execute(CallAPI.uploadURL, getResources().getString(R.string.appID), currentLessonID+"", pathToTempFile, CallAPI.IP);
The problem is that according to the response from the server, it recieves no image at all. This is a part of code that is responsible for the answer that I currently recieve:
if(!isset($_FILES['pic'])) ex_fail("pic not set");
if($_FILES['pic']['error'] != 0) ex_fail("pic upload error ");
I get "pic not set" error. Though according to the logs, I actually write the image into DataOutputStream, I compared the bytes count - it is the same.
What could cause the problem?
I'm trying to POST an image to a PHP file from my android app and am wondering what format (File, Fileoutputstream etc) I have to post it in for it to be recognized as a file and refer to it with $_FILE['filename'] in my php script.
Thanks :)
EDIT:
Sorry I may not have been clear, I'm not looking for the PHP script, I already have that finished accepting the $_FILE['sample'] and doing what I need with it, I'm just not sure the file TYPE that I have to post to the php file (IN JAVA) in order for php to 'see' it as $_FILE
FYI: I am using the loopj asynchronous http request library.
public void add_image_android(final Bitmap image, String party_id, String guest_id)
{
String url = "http://www.mysite.com/urltopost";
/* not sure what to set fOut to for the bitmap to be passed as file */
RequestParams params = new RequestParams();
params.put("file", fOut);
params.put("guest_id", guest_id);
params.put("party_id", party_id);
client.post(url, params, new JsonHttpResponseHandler()
{
#Override
public void onSuccess(JSONObject response)
{
((ResponseListener)_mainContext).add_image_android_response(response.toString());
return;
}
#Override
public void onFailure(Throwable e)
{
fireToast("api error:"+e);
Log.d("api error:",e.toString());
}
});
}
Try the Below Code which will upload the Image and Give the Link.
<?php
$uploaddir = 'images/';
$ran = rand () ;
$file = basename($_FILES['userfile']['name']);
$uploadfile = $uploaddir .$ran.$file;
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "http://www.domain.com/folder/{$uploadfile}";
}
?>
This worked for me: (very old code, hope it helps...)
ReturnObject returnObject = new ReturnObject();
HttpURLConnection conn = null;
DataOutputStream dos = null;
BufferedReader inStream = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
String urlString = "your url";
try{
FileInputStream fileInputStream = new FileInputStream(photoFile);
URL url = new URL(urlString);
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
dos = new DataOutputStream( conn.getOutputStream() );
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"image\";"
+ " filename=\"" + photoFile.getAbsolutePath() +"\"" + lineEnd);
dos.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0){
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
fileInputStream.close();
dos.flush();
dos.close();
}catch (MalformedURLException ex){
ex.printStackTrace();
}catch (IOException ioe){
ioe.printStackTrace();
}
On the server i found this:
$source = $_FILES['image']['tmp_name'];
move_uploaded_file($source, $target)
Not sure what this "tmp_name" is...
I my app I am trying to send an image over a PHP server. The problem is the PHP programmers say that it should be sent as an data. Following is the code which I am currently using, please help me to convert the image to a data and get a response from the server.
InputStream is;
private int serverResponseCode;
private String serverResponseMessage;
#Override
public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
setContentView(R.layout.main);
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
DataInputStream inputStream = null;
String pathToOurFile = "/sdcard/siva.PNG";
Log.e("pathToOurFile",""+pathToOurFile);
String urlServer = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/upload.php";
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
Log.e("URL Server",""+urlServer);
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
Log.e("maxBufferSize",""+maxBufferSize);
try
{
FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile) );
Log.e("FIS",""+fileInputStream);
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)
Log.e("con",String.valueOf(connection.getDoOutput()));
serverResponseCode = connection.getResponseCode();
serverResponseMessage = connection.getResponseMessage();
Log.e("response",""+serverResponseCode);
Log.e("serverResponseMessage",""+serverResponseMessage);
fileInputStream.close();
outputStream.flush();
outputStream.close();
}
catch (Exception ex)
{
Log.e("Exception Handling",""+ex);
}
}
Atlast i found the answer, i did a small mistake....In the above code i have changed only one word in the following line
outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + pathToOurFile +"\"" + lineEnd);
In the above line the main part is the word "uploadedfile". This word must be specified by the php programmer or else the file which we are sending will not be replaced.
Please refer the here