ServerResponse 404 while uploading image to server - android

I want to upload Image to Perticular Url(www.myUrl.com/myFolderName/) through android and retrieve the address of that url.
Here is my code
class SaveFile extends AsyncTask<String,String,String>
{
FileInputStream fileInputStream;
HttpURLConnection connection;
URL url;
DataOutputStream outputStream;
int bytesRead,bytesAvailable,bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File selectedFile = new File(selectedImagePath);
//selectedImagePath = path of Image in phonememory
#Override
protected String doInBackground(String... params)
{
Log.v(TAG,"Image path is " + selectedImagePath);
try
{
fileInputStream = new FileInputStream(selectedFile);
url = new URL(SEND_IMAGE);
connection= (HttpURLConnection)url.openConnection();
Log.v(TAG,"connection established");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection","Keep-Alive");
connection.setRequestProperty("ENCTYPE","multipart/form-data");
connection.setRequestProperty("Content-Type","multipart/form-data;boundary=*****");
//connection.setRequestProperty("image1",selectedImagePath);
//connection.setRequestProperty("user_id","1");
outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes("--*****\r\n");
outputStream.writeBytes("Content-Disposition:form-data;name=\"uploaded_file\";filename=\""+selectedImagePath+"\""+"\r\n");
outputStream.writeBytes("\r\n");
//outputStream.writeBytes("--*****\r\n");
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable,maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = fileInputStream.read(buffer,0,bufferSize);
while (bytesRead>0)
{
outputStream.write(buffer,0,bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable,maxBufferSize);
bytesRead = fileInputStream.read(buffer,0,bufferSize);
}
outputStream.writeBytes("\r\n");
outputStream.writeBytes("--*****--\r\n");
int serverResponseCode = connection.getResponseCode();
String serverResponseMessage = connection.getResponseMessage();
if(serverResponseCode == HttpURLConnection.HTTP_OK) {
String line;
StringBuilder sb = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line = reader.readLine()) != null) {
sb.append(line);
}
Log.v(TAG,"Response is " +sb.toString());
}
Log.v("UploadImage", "Server Response is: " + serverResponseMessage + ": " + serverResponseCode);
fileInputStream.close();
outputStream.flush();
outputStream.close();
}
catch (Exception e)
{
Log.v("UploadImage"," " + e.toString());
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}
but I am getting serverResponse 404
I tried solutions like Uploading Image to Server - Android but not worked.
I searched a lot.but couldnt find solution
Please Help!!

I want to say that this maybe a server error. 404 in most cases is an error that says, "you have used wrong url". Check whether this url is correct.try to upload your data in your browser.

Related

Android Java file upload to Django backend

I have tried relentlessly to create a succesfull file upload from my JAVA/Android project to Django/Python backend.
The file I am trying to upload is a wav audio file which is stored on the phone.
I am trying to mix two sets of code.
The Android code I am using is the one taken from: How to upload a WAV file using URLConnection.
public class curlAudioToWatson extends AsyncTask<String, Void, String> {
String asrJsonString="";
#Override
protected String doInBackground(String... params) {
String result = "";
try {
Log.d("Msg","**** UPLOADING .WAV to ASR...");
URL obj = new URL(ASR_URL);
HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
//conn.setRequestProperty("X-Arg", "AccessKey=3fvfg985-2830-07ce-e998-4e74df");
conn.setRequestProperty("Content-Type", "audio/wav");
conn.setRequestProperty("enctype", "multipart/form-data");
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
String wavpath=mRcordFilePath;
File wavfile = new File(wavpath);
boolean success = true;
if (wavfile.exists()) {
Log.d("Msg","**** audio.wav DETECTED: "+wavfile);
}
else{
Log.d("Msg","**** audio.wav MISSING: " +wavfile);
}
String charset="UTF-8";
String boundary = Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value.
String CRLF = "\r\n"; // Line separator required by multipart/form-data.
OutputStream output=null;
PrintWriter writer=null;
try {
output = conn.getOutputStream();
writer = new PrintWriter(new OutputStreamWriter(output, charset), true);
byte [] music=new byte[(int) wavfile.length()];//size & length of the file
InputStream is = new FileInputStream (wavfile);
BufferedInputStream bis = new BufferedInputStream (is, 16000);
DataInputStream dis = new DataInputStream (bis); // Create a DataInputStream to read the audio data from the saved file
int i = 0;
copyStream(dis,output);
}
catch(Exception e){
}
conn.connect();
int responseCode = conn.getResponseCode();
Log.d("Msg","POST Response Code : " + responseCode + " , MSG: " + conn.getResponseMessage());
if (responseCode == HttpURLConnection.HTTP_OK) { //success
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
Log.d("Msg","***ASR RESULT: " + response.toString());
JSONArray jresponse=new JSONObject(response.toString()).getJSONObject("Recognition").getJSONArray("NBest");
asrJsonString=jresponse.toString();
for(int i = 0 ; i < jresponse.length(); i++){
JSONObject jsoni=jresponse.getJSONObject(i);
if(jsoni.has("ResultText")){
String asrResult=jsoni.getString("ResultText");
//ActionManager.getInstance().addDebugMessage("ASR Result: "+asrResult);
Log.d("Msg","*** Result Text: "+asrResult);
result = asrResult;
}
}
Log.d("Msg","***ASR RESULT: " + jresponse.toString());
} else {
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
Log.d("Msg","POST FAILED: " + response.toString());
result = "";
}
} catch (Exception e) {
Log.d("Msg","HTTP Exception: " + e.getLocalizedMessage());
}
return result; //"Failed to fetch data!";
}
#Override
protected void onPostExecute(String result) {
if(!result.equals("")){
Log.d("Msg","onPostEXECUTE SUCCESS, consuming result");
//sendTextInputFromUser(result);
//ActionManager.getInstance().addDebugMessage("***ASR RESULT: "+asrJsonString);
runOnUiThread(new Runnable() {
#Override
public void run() {
}
});
}else{
Log.d("Msg","onPostEXECUTE FAILED" );
}
}
}
public void copyStream( InputStream is, OutputStream os) {
final int buffer_size = 4096;
try {
byte[] bytes = new byte[buffer_size];
int k=-1;
double prog=0;
while ((k = is.read(bytes, 0, bytes.length)) > -1) {
if(k != -1) {
os.write(bytes, 0, k);
prog=prog+k;
double progress = ((long) prog)/1000;///size;
Log.d("Msg","UPLOADING: "+progress+" kB");
}
}
os.flush();
is.close();
os.close();
} catch (Exception ex) {
Log.d("Msg","File to Network Stream Copy error "+ex);
}
}
The Django backend code is taken from: https://simpleisbetterthancomplex.com/tutorial/2016/08/01/how-to-upload-files-with-django.html and I am using the simple upload:
def simple_upload(request):
if request.method == 'POST' and request.FILES['myfile']:
myfile = request.FILES['myfile']
fs = FileSystemStorage()
filename = fs.save(myfile.name, myfile)
uploaded_file_url = fs.url(filename)
return render(request, 'core/simple_upload.html', {
'uploaded_file_url': uploaded_file_url
})
return render(request, 'core/simple_upload.html')
I have already disabled the need for CSRF using #csrf_exempt.
I am getting the error "MultiValueDictKeyError" since Java does not post the file with the name 'myfile' for request.FILES['myfile'] to catch. Is have tried removing the ['myfile'] and just use request.FILES but then I get an error on
filename = fs.save(myfile.name, myfile)
saying there is no name to fetch.
Can I post the file so that it it catched by
request.FILES['myfile']
or is there better/simpler Django backend-code to use for communication with Android/IOS.
Thanks in advance and I apologize if this is a stupid question but I am dead stuck.
Here I go again answering my own question.
I found the following code from Android:How to upload .mp3 file to http server?
Using that instead of How to upload a WAV file using URLConnection and changing the line: dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + existingFileName + "\"" + lineEnd);
To dos.writeBytes("Content-Disposition: form-data; name=\"myfile\";filename=\"" + existingFileName + "\"" + lineEnd);
fixed my problem.

Uploading Image to Server - Android

I have got the Rest Api's link and the sample code for uploading the image in C sharp but how to upload image to server from android the same thing using java
Here's that sample code
http://xx.xx.xxx.xx/restservice/photos
Sample code for uploading file:
string requestUrl = string.Format("{0}/UploadPhoto/{1}", url,filnm);
//file name should be uniqque
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(requestUrl);
request.Method = "POST";
request.ContentType = "text/plain";
byte[] fileToSend = FileUpload1.FileBytes; //File bytes
request.ContentLength = fileToSend.Length;
using (Stream requestStream = request.GetRequestStream())
{
// Send the file as body request.
requestStream.Write(fileToSend, 0, fileToSend.Length);
requestStream.Close();
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
Console.WriteLine("HTTP/{0} {1} {2}", response.ProtocolVersion, (int)response.StatusCode, response.StatusDescription);
how you will you do it with the android
EDITED:
With the help of your answer I have written the code over here but I am getting 404 connection response and the ERROR ERROR
public class ImageUploadToServer extends Activity {
TextView messageText;
Button uploadButton;
String upLoadServerUri = null;
String urlLink = "http://xx.xx.xxx.xx/restservice/photos/";
String path= Environment.getExternalStorageDirectory().getAbsolutePath()+"/myimg.jpg";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload_to_server);
uploadButton = (Button)findViewById(R.id.uploadButton);
messageText = (TextView)findViewById(R.id.messageText);
uploadData();
}
public void uploadData ()
{
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
try {
// FileInputStream fileInputStream = new FileInputStream(new File(path));
File sourceFile = new File(path);
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(urlLink);
connection = (HttpURLConnection) url.openConnection();
Log.d("Connection:", "Connection" + connection.getResponseCode());
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
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=\""
+ path + "\"" + lineEnd);
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens
+ lineEnd);
fileInputStream.close();
outputStream.flush();
outputStream.close();
InputStream responseStream = new BufferedInputStream(connection.getInputStream());
BufferedReader responseStreamReader = new BufferedReader(new InputStreamReader(responseStream));
String line = "";
StringBuilder stringBuilder = new StringBuilder();
while ((line = responseStreamReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
responseStreamReader.close();
String response = stringBuilder.toString();
Log.w("SERVER RESPONE: ", "Server Respone" + response);
responseStream.close();
connection.disconnect();
} catch (Exception ex) {
Log.i("UPLOAD ERROR", "ERROR ERROR");
}
}
}
I am currently using this code to upload small videos to server (PHP server side).
Take not that the apache HttpClient is not supported anymore, so HttpURLConnection is the way to go.
try {
FileInputStream fileInputStream = new FileInputStream(new File(
path));
URL url = new URL(urlLink);
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
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=\""
+ path + "\"" + lineEnd);
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens
+ lineEnd);
fileInputStream.close();
outputStream.flush();
outputStream.close();
InputStream responseStream = new BufferedInputStream(connection.getInputStream());
BufferedReader responseStreamReader = new BufferedReader(new InputStreamReader(responseStream));
String line = "";
StringBuilder stringBuilder = new StringBuilder();
while ((line = responseStreamReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
responseStreamReader.close();
String response = stringBuilder.toString();
Log.w("SERVER RESPONE: ", response);
responseStream.close();
connection.disconnect();
} catch (Exception ex) {
Log.i("UPLOAD ERROR", "ERROR ERROR");
}
}
here is the PHP that may help you for receiving the file on your server.
<?php
try {
// Checking for upload attack and rendering invalid.
if (
!isset($_FILES['uploadedfile']['error']) ||
is_array($_FILES['uploadedfile']['error'])
) {
throw new RuntimeException('Invalid parameters.');
}
// checking for error value on upload
switch ($_FILES['uploadedfile']['error']) {
case UPLOAD_ERR_OK:
break;
case UPLOAD_ERR_NO_FILE:
throw new RuntimeException('No file sent.');
case UPLOAD_ERR_INI_SIZE:
case UPLOAD_ERR_FORM_SIZE:
throw new RuntimeException('Exceeded filesize limit.');
default:
throw new RuntimeException('Unknown errors.');
}
// checking file size
if ($_FILES['uploadedfile']['size'] > 1000000) {
throw new RuntimeException('Exceeded filesize limit.');
}
// checking MIME type for mp4... change this to suit your needs
$finfo = new finfo(FILEINFO_MIME_TYPE);
if (false === $ext = array_search(
$finfo->file($_FILES['uploadedfile']['tmp_name']),
array(
'mp4' => 'video/mp4',
),
true
)) {
throw new RuntimeException('Invalid file format.');
}
// Uniquely naming each uploaded for file
if (!move_uploaded_file(
$_FILES['uploadedfile']['tmp_name'],
sprintf('./uploads/%s.%s',
sha1_file($_FILES['uploadedfile']['tmp_name']),
$ext
)
)) {
throw new RuntimeException('Failed to move uploaded file.');
}
// response code.
echo 'File is uploaded successfully!';
}
catch (RuntimeException $e) {
echo $e->getMessage();
}
?>
try this....
public static JSONObject postFile(String url,String filePath,int id){
String result="";
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
File file = new File(filePath);
MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(file, "image/jpeg");
StringBody stringBody= null;
JSONObject responseObject=null;
try {
stringBody = new StringBody(id+"");
mpEntity.addPart("file", cbFile);
mpEntity.addPart("id",stringBody);
httpPost.setEntity(mpEntity);
System.out.println("executing request " + httpPost.getRequestLine());
HttpResponse response = httpClient.execute(httpPost);
HttpEntity resEntity = response.getEntity();
result=resEntity.toString();
responseObject=new JSONObject(result);
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
catch (ClientProtocolException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
catch (JSONException e) {
e.printStackTrace();
}
return responseObject;
}

Android post file array

I have tried to post multiple file to web service. But, single file post working multiple file post not working.
Please help me any one. How to implement that feature.
I have tried the below code. Please check it.
String fileName = sourceFileUri;
String fileName1 = sourceFileUri1;
// fileName1 - how to post to web service
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File(sourceFileUri);
if (!sourceFile.isFile()) {
dialog.dismiss();
Log.e("uploadFile", "Source File not exist :" + imagepath);
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("Source File not exist :" + imagepath);
}
});
return 0;
} else {
try {
// open a URL connection to the Servlet
URL url = new URL(upLoadServerUri);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("uploaded_file[]", fileName);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file[]\";filename=\""
+ fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
FileInputStream fileInputStream = new FileInputStream(
sourceFile);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
// close the streams //
fileInputStream.close();
dos.flush();
dos.close();
InputStream is = conn.getInputStream();
// retrieve the response from server
int ch;
StringBuffer b = new StringBuffer();
while ((ch = is.read()) != -1) {
b.append((char) ch);
}
String s = b.toString();
Log.i("Response", s);
} catch (MalformedURLException ex) {
dialog.dismiss();
ex.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
messageText
.setText("MalformedURLException Exception : check script url.");
Toast.makeText(MainActivity.this,
"MalformedURLException", Toast.LENGTH_SHORT)
.show();
}
});
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
dialog.dismiss();
e.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("Got Exception : see logcat ");
Toast.makeText(MainActivity.this,
"Got Exception : see logcat ",
Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server Exception",
"Exception : " + e.getMessage(), e);
}
dialog.dismiss();
return serverResponseCode;
}
If you want to pass an array of FileBody, you can try it like,
reqEntity.addPart("file[]["+i+"]", bab);
This will generate params like
file=>[{"1" => "File" },{"2" => "File"}..]
Hope it clarifies your doubt.
I got solution. I have used like as below. It's working.
public void uploadFileNew(ArrayList<String>IMAGEPTHLIST, ArrayList<String>IMAGENAMELIST) {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(upLoadServerUri);
ByteArrayBody bab;
ByteArrayOutputStream bos;
Bitmap bm;
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
for(int i = 0 ; i< IMAGEPTHLIST.size() ; i++) {
bm = BitmapFactory.decodeFile(IMAGEPTHLIST.get(i));
bos = new ByteArrayOutputStream();
bm.compress(CompressFormat.PNG, 100, bos);
byte[] data = bos.toByteArray();
bab = new ByteArrayBody(data, IMAGENAMELIST.get(i));
reqEntity.addPart("file["+i+"]", bab);
}
reqEntity.addPart("cat_id", new StringBody("123"));
reqEntity.addPart("name", new StringBody("Android test"));
postRequest.setEntity(reqEntity);
HttpResponse response2 = httpClient.execute(postRequest);
BufferedReader reader = new BufferedReader(new InputStreamReader(response2.getEntity().getContent(), "UTF-8"));
String sResponse;
StringBuilder s = new StringBuilder();
while ((sResponse = reader.readLine()) != null) {
s = s.append(sResponse);
}
System.out.println("===="+s.toString());
} catch (Exception e) {
e.printStackTrace();
}
dialog.dismiss();
}

How to send file through http post method without additional info?

I am sending a file from sd card by using the following code.
HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
String existingFileName = Environment.getExternalStorageDirectory().getAbsolutePath()
+ "/111";
File f = new File(existingFileName);
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.178.1.7/Geo/Prodect(filename)";
try
{
//------------------ CLIENT REQUEST
FileInputStream fileInputStream = new FileInputStream(f);
// 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);
}
It works fine but,the file contains 20 lines it saved in the sever with 22 lines.
My actual file looks like as follows.
android app info
app name
app time
when i will send the flle to server from sd card the file look like as follows
1)**mnt/sdcard/111**
android app info
app name
app time
2)**
1 and 2 lines are added.
How i can send a file without those two lines .
If any one know the solution please help me .
Thanks in advance..
public static StringBuffer post(String url,InputStream in) throws IOException {
InputStream bufferInputStream = null;
InputStreamReader responseInputStream = null;
HttpURLConnection conn = null;
OutputStream requestOutputStream = null;
StringBuffer responseString = new StringBuffer();
int bufferSize = 8192;
byte[] byteBuffer = new byte[bufferSize];
int postDataSize = 0;
try {
if (in != null) {
bufferInputStream = new BufferedInputStream(in);
}
if (bufferInputStream != null) {
postDataSize = bufferInputStream.available();
}
//send request
conn = getConnecttion(url);
if (postDataSize > 0) {
requestOutputStream = conn.getOutputStream();
int position = 0;
while ((position = bufferInputStream.read(byteBuffer)) > -1) {
requestOutputStream.write(byteBuffer, 0, position);
}
requestOutputStream.flush();
requestOutputStream.close();
requestOutputStream = null;
byteBuffer = null;
}
// get response
int responseCode = conn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
responseInputStream = new InputStreamReader(conn.getInputStream(),"UTF-8");
char[] charBuffer = new char[bufferSize];
int _postion = 0;
while ((_postion=responseInputStream.read(charBuffer)) > -1) {
responseString.append(charBuffer,0,_postion);
}
responseInputStream.close();
responseInputStream = null;
charBuffer = null;
}else{
throw new IOException("Respsone code:"+responseCode);
}
} catch (Exception e) {
e.printStackTrace();
throw new IOException(e.getMessage());
} finally {
byteBuffer = null;
if (responseInputStream != null) {
responseInputStream.close();
responseInputStream = null;
}
if (conn != null) {
conn.disconnect();
conn = null;
}
if (requestOutputStream != null) {
requestOutputStream.close();
requestOutputStream = null;
}
if (bufferInputStream != null) {
bufferInputStream.close();
bufferInputStream = null;
}
}
return responseString;
}
Please reference to above simple code,
send file like this:post("http://youurl.com",new FileInputStream(" you file path"))
Try commenting the following
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes(lineEnd);

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

Categories

Resources