I am trying to upload file to a php server from my android device. There is thread with same question but he is using a different method. My Android side code works fine and shows no error message but server is not receiving any file. here is my sample code, I found it online.
import java.io.FileInputStream;
import android.app.Activity;
import android.os.Bundle;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.util.Log;
public class uploadfile extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
doFileUpload();
}
private void doFileUpload(){
HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
String exsistingFileName = "/sdcard/def.jpg";
// Is this the place are you doing something wrong.
String lineEnd = "rn";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
String responseFromServer = "";
String urlString = "http://192.168.1.6/index.php";
try
{
//------------------ CLIENT REQUEST
Log.e("MediaPlayer","Inside second Method");
FileInputStream fileInputStream = new FileInputStream(new File(exsistingFileName) );
// open a URL connection to the Servlet
URL url = new URL(urlString);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
// Allow Inputs
conn.setDoInput(true);
// Allow Outputs
conn.setDoOutput(true);
// Don't use a cached copy.
conn.setUseCaches(false);
// Use a post method.
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
dos = new DataOutputStream( conn.getOutputStream() );
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\""
+ exsistingFileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
Log.e("MediaPlayer","Headers are written");
// 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("MediaPlayer","File is written");
fileInputStream.close();
dos.flush();
dos.close();
}
catch (MalformedURLException ex)
{
Log.e("MediaPlayer", "error: " + ex.getMessage(), ex);
}
catch (IOException ioe)
{
Log.e("MediaPlayer", "error: " + ioe.getMessage(), ioe);
}
//------------------ read the SERVER RESPONSE
try {
inStream = new DataInputStream ( conn.getInputStream() );
String str;
while (( str = inStream.readLine()) != null)
{
Log.e("MediaPlayer","Server Response"+str);
}
inStream.close();
}
catch (IOException ioex){
Log.e("MediaPlayer", "error: " + ioex.getMessage(), ioex);
}
}
}
and my php server side code is as follows
<?php
$target_path = "uploads/";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
}
else{
echo "There was an error uploading the file, please try again!";
}
?>
Apache is running. When i run server, this error msg appears There was an error uploading the file, please try again!. I have checked the log data in eclipse and what i think is the socket problem but i am not sure. Please help if anyone knows the solution.
11-28 05:37:55.310: DEBUG/SntpClient(59): request time failed: java.net.SocketException: Address family not supported by protocol
It seems that the server is not responding to the client. Try uploading using an ftp connection through the Android application, if that works then check your Apache configuration on accepting connections and the writable directories. When I had a similar problem it turned out that my directory gave no write privileges.
Is the error from Java or from Apache?
Change your code in the following way for the correct escape sequences:
Replace
String lineEnd = "rn";
with
String lineEnd = "\r\n";
Related
I want to upload mp3 file from Android app to my asp.net server, I am using this class on client side
import android.util.Log;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class HttpFileUpload implements Runnable{
URL connectURL;
String responseString;
String Title;
String Description;
byte[ ] dataToServer;
FileInputStream fileInputStream = null;
public HttpFileUpload(String urlString, String vTitle, String vDesc){
try{
connectURL = new URL(urlString);
Title= vTitle;
Description = vDesc;
}catch(Exception ex){
Log.i("HttpFileUpload","URL Malformatted");
}
}
public void Send_Now(FileInputStream fStream){
fileInputStream = fStream;
Sending();
}
void Sending(){
String iFileName = "temp.mp3";
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);
}
}
#Override
public void run() {
// TODO Auto-generated method stub
}
}
Then I using the above class like that
public void uploadFile(){
try {
File appDir = getContext().getExternalFilesDirs(null)[0];
File file = new File(appDir.getAbsolutePath() + "/Audios");
if (!file.exists()) {
file.mkdirs();
}
fileName = appDir.getAbsolutePath() + "/Audios/temp.mp3";
FileInputStream fstrm = new FileInputStream(fileName);
// Set your server page url (and the file title/description)
HttpFileUpload hfu = new HttpFileUpload("http://www.example.com/Fileup.aspx", "my file title","my file description");
hfu.Send_Now(fstrm);
} catch (FileNotFoundException e) {
// Error: File not found
}
}
And this is the server side asp.net code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Fileup : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Page_Init(object sender, EventArgs e)
{
string vTitle = "";
string vDesc = "";
string FilePath = Server.MapPath("~/files/cur_file.mp3");
if (!string.IsNullOrEmpty(Request.Form["title"]))
{
vTitle = Request.Form["title"];
}
if (!string.IsNullOrEmpty(Request.Form["description"]))
{
vDesc = Request.Form["description"];
}
HttpFileCollection MyFileCollection = Request.Files;
if (MyFileCollection.Count > 0)
{
// Save the File
MyFileCollection[0].SaveAs(FilePath);
}
}
}
Notes:
I added INTERNET & EXTERNAL STORAGE permission to my client app
The client side reaches to this line and return code 500 Log.e(Tag,"File Sent, Response: "+String.valueOf(conn.getResponseCode())); and then throw exception in the next line InputStream is = conn.getInputStream();
Then I can't find the mp3 file in "files" folder on my Server
The mp3 file just 16 kb
What is the problem?
I solved it, There was no permission to write files for the folder "files", Thanks
I take a picture using the android.hardware.Camera API. I then convert it to a Bitmap of half the actual size, compress it to a JPEG of quality 80, convert it to Base64 and send it to the server as follows.
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 80, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream.toByteArray();
String encoded = Base64.encodeToString(byteArray, Base64.NO_WRAP);
String json_response = "";
try {
URL url = new URL("https://example.com/api_endpoint");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write("?reg=" + regCode);
writer.write("&img=" + encoded);
writer.flush();
writer.close();
os.close();
Log.d("Auth", conn.getResponseCode() + "");
InputStreamReader in = new InputStreamReader(conn.getInputStream());
BufferedReader br = new BufferedReader(in);
String text = "";
while ((text = br.readLine()) != null) {
json_response += text;
}
conn.disconnect();
} catch (IOException e) {
Log.d(getClass().getName(), "" + e.getMessage());
}
This works as expected. Now, If I don't resize the image and keep the quality 100%, how should I go about to avoid an OutOfMemoryError? My application requires the image to be in the full resolution and best quality possible.
My questions are:
Is the way I am uploading the correct way?
How to send Image is best quality without OutOfMemoryError i.e. how to optimize RAM usage in this process?
Here is my image/file uploader class:
public class ImageUploader extends AsyncTask<String, String, String> {
File imageFile = null;
String fileName = null;
public ImageUploader(File imageFile, String fileName){
this.imageFile = imageFile;
this.fileName = fileName;
}
#Override
protected String doInBackground(String... params) {
String url_str = params[0];
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
String Tag="fSnd";
try {
URL url = new URL(url_str);
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("POST");
c.setDoInput(true);
c.setDoOutput(true);
c.setRequestProperty("Connection", "Keep-Alive");
c.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
c.connect();
DataOutputStream dos = new DataOutputStream(c.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\"" + this.fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
FileInputStream fin = new FileInputStream(imageFile);
int bytesAvailable = fin.available();
int maxBufferSize = 1024;
int bufferSize = Math.min(bytesAvailable, maxBufferSize);
byte[ ] buffer = new byte[bufferSize];
int bytesRead = fin.read(buffer, 0, bufferSize);
while (bytesRead > 0)
{
dos.write(buffer, 0, bufferSize);
bytesAvailable = fin.available();
bufferSize = Math.min(bytesAvailable,maxBufferSize);
bytesRead = fin.read(buffer, 0,bufferSize);
}
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
fin.close();
dos.flush();
dos.close();
StringBuilder response = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(c.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
return response.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
}
return null;
}
}
Usage:
new ImageUploader(pictureFile, "sample.jpg"){
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_LONG).show();
}
}.execute("http://example/upload.php");
PHP:
<?php
$file = explode('.', $_FILES['file']['name']);
$ext = $file[count($file) - 1];
$name = substr($_FILES['file']['name'], 0, (strlen($ext) + 1) * -1);
$location = 'images/';
$cntr = 1;
$tmp_name = $name;
if(move_uploaded_file($_FILES['file']['tmp_name'], $location.$tmp_name.'.'.$ext)){
echo "Image was uploaded.";
}else{
echo "Image was not uploaded.";
}
?>
If you have the control over the API endpoint. Then try to implement the POST request to accept multi-part uploading from client side.
On client-side, have something like this to upload the image to API (with Okhttp client)
private static final String IMGUR_CLIENT_ID = "...";
private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception {
// Use the imgur image upload API as documented at https://api.imgur.com/endpoints/image
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("title", "Square Logo")
.addFormDataPart("image", "logo-square.png",
RequestBody.create(MEDIA_TYPE_PNG, new File("website/static/logo-square.png")))
.build();
Request request = new Request.Builder()
.header("Authorization", "Client-ID " + IMGUR_CLIENT_ID)
.url("https://api.imgur.com/3/image")
.post(requestBody)
.build();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println(response.body().string());
}
I think problem not with downloading to server. If I understand correctly, you getting image from camera and sending it. Note, that if you using simple request intent, that returns in onActivityResult() - Bitmap Image - this may be point of OutOfMemoryException...
Solution it's use another form on Intent() method, (that can get storage path in his parameters) for getting photo from camera, that doesn't return Bitmap image. But save photo to path, which you specified. And now you can do anything with photo in path, without OutOfMemoryException...
Sample starting correct Intent:
File destination = new File(Environment.getExternalStorageDirectory(),
"image.jpg");
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(destination));
startActivityForResult(intent, CAMERA_PICTURE);
Let me know, this helps...
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I want to send images from android device to my web application running on server with tomcat. please help me in writing small code for sending image to a REST web service running on Web server. Please provide me the sample code if possible. I am stuck with what method to use. Any help would be greatly appreciated. thanks in advance.
Edit: The answer for this question is as follows
while(it.hasNext()){
File file = new File((new StringBuilder()).append(Environment.getExternalStorageDirectory()).append(File.separator).append("jcms").append(File.separator).append("Customer_").append( customer.getId()).toString());
File[] listOfFiles = file.listFiles();
for(int i=0;i<listOfFiles.length;i++){
JSONObject message = new JSONObject();
File fil=listOfFiles[i];
FileInputStream imageInFile = new FileInputStream(fil);
byte imageData[] = new byte[(int)fil.length()];
imageInFile.read(imageData);
String imageDataString = encodeImage(imageData);
URL url=new URL(ClearCustomersContract.CLEAR_SERVER_URL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestMethod("POST");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
out.write(imageDataString);
out.close();
BufferedReader in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
while (in.readLine() != null) {
}
in.close();
}
}
And The REST Webservice on server side is like
#Override
#POST
#Consumes({MediaType.APPLICATION_JSON,MediaType.APPLICATION_OCTET_STREAM})
#Path("/getData")
public Response getAllTheSyncData(InputStream incomingData) {
StringBuilder sb = new StringBuilder();
try {
BufferedReader in = new BufferedReader(new InputStreamReader(incomingData));
String line = null;
while ((line = in.readLine()) != null) {
sb.append(line);
}
} catch (Exception e) {
System.out.println("Error Parsing: - ");
}
return Response.status(200).entity("Success").build();
}
and this is how we convert the string back to image.
byte[] imageByteArray = decodeImage(jsonObj.get("imageData").toString());
imageOutFile = new FileOutputStream(
"C:/Users/SUNILKUMAR/Desktop/result.jpg");
// Write a image byte array into file system
imageOutFile.write(imageByteArray);
imageOutFile.close();
Check the link . it gives complete example of how to upload file to server.
or check below 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(){
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)
{
Log.e(Tag, "IO error: " + ioe.getMessage(), ioe);
}
}
#Override
public void run() {
// TODO Auto-generated method stub
}
}
public void UploadFile(){
try {
// Set your file path here
FileInputStream fstrm = new FileInputStream(Environment.getExternalStorageDirectory().toString()+"/DCIM/file.mp4");
// Set your server page url (and the file title/description)
HttpFileUpload hfu = new HttpFileUpload("http://www.myurl.com/fileup.aspx", "my file title","my file description");
hfu.Send_Now(fstrm);
} catch (FileNotFoundException e) {
// Error: File not found
}
}
You can use below code to upload image with REST webservice
try {
HttpClient httpClient = new DefaultHttpClient();
HttpContext httpContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(
"YOUR WEB SERVICE URL");
entity = getMultipleEntityUpload();
httpPost.setEntity(entity);
HttpResponse httpResponse = httpClient.execute(httpPost,
httpContext);
HttpEntity httpEntity = httpResponse.getEntity();
InputStream is = httpEntity.getContent();
String line = "";
StringBuilder total = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(
is));
while ((line = rd.readLine()) != null) {
total.append(line);
}
String result =total.toString();
} catch (Exception e) {
// TODO: handle exception
}
private MultipartEntity getMultipleEntityUpload() {
MultipartEntity entity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
try {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
//imagePic is bitmap of your image
imagePic.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] arrByteImage = stream.toByteArray();
try {
entity.addPart(WS_Key_Constant.KEY_IMAGE, new ByteArrayBody(
arrByteImage, ".jpg"));
} catch (Exception e) {
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return entity;
}
I have written out a program which is designed to upload text files created from motion data information to a PHP cloud server that I have set up with 000webhost.com. Ive tried running it however it will not run for some reason. None of the sensor information is uploaded and there seems to be a problem me thinks on the server end. Is the error in the script or code? (or both?).
Edit: Yeah I know its not "great", I am still fairly new to coding and been trying to fiddle around with the code for a while (still working on it).
Program
package com.example.motionsense3;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.TimerTask;
import android.content.Context;
import android.os.Bundle;
import android.widget.Toast;
import java.net.URL;
import java.net.HttpURLConnection;
import java.io.DataOutputStream;
import java.io.File;
import android.util.Log;
public class SaveTimer extends TimerTask
{
String upLoadServerUri = null;
final String uploadFilePath = "/data/data/com.example.motionsense3/";
//final String uploadFileName = "????";
private ArrayList<String> motionData;
private ArrayList<String> motionDataClone;
private Context context;
public SaveTimer(ArrayList<String> motionData, MainActivity context) {
this.motionDataClone = (ArrayList<String>) motionData.clone();
this.motionData = motionData;
this.context = context;
}
#Override
public void run() {
Log.e("DIDUPLOADWORK", Boolean.toString(upload()));
}
private void save() {
try {
this.motionDataClone = (ArrayList<String>) motionData.clone();
motionData.clear();
FileOutputStream fileOutput = context.openFileOutput("scaninfo_" + new SimpleDateFormat("dd_MM_yyyy_HH_mm_ss").format(new Date()).toString(), context.MODE_WORLD_READABLE);//.write(s);
for(String s : motionDataClone)
{
fileOutput.write(s.getBytes());
}
fileOutput.close();
} catch (Exception e) {
}
//save();
}
public boolean upload(){//ArrayList<String> motion){//String sourceFileUri) {
/************* Php script path ****************/
upLoadServerUri = "motionsense.uphero.com/public_html/motiondata/UploadToServer.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;
try {
URL url = new URL(upLoadServerUri);
String fileName = "scaninfo_" + new SimpleDateFormat("dd_MM_yyyy_HH_mm_ss").format(new Date()).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
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);
for(String s : motionDataClone)
{
dos.write(s.getBytes());
}
// 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.e("SERVERRESPONSE", serverResponseMessage);
Log.e("SERVERRESPONSECODE", String.valueOf(serverResponseCode));
}
catch(Exception e){return false;}
return true;
}
}
Php script
<?php
$file_path = "motiondata/";
$file_path = $file_path . basename( $_FILES['uploaded_file']['name']);
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path)) {
echo "success";
} else{
echo "fail";
}
?>
Just quickly glancing through the code, I believe your problem is here:
upLoadServerUri = "motionsense.uphero.com/public_html/motiondata/UploadToServer.php";
Basically you're trying to make a connection to UploadToServer.php through this public_html directory, however, this directory doesn't exist publically (it's where your "root" files are served from when accessing a website with '/'). Change to:
upLoadServerUri = "motionsense.uphero.com/motiondata/UploadToServer.php";
And you should be fine (assuming everything else works haha).
I have a web service that get a audio and do some operation on it and finally returns a string ,this web service have a web page like this
<form name="form1" method="post" action="Default.aspx" id="form1" enctype="multipart/form-data">
<input type="file" name="FileUpload3" id="FileUpload3" style="width:325px;" />
<input type="submit" name="Button6" value="Upload File" id="Button6" />
<span id="Label1"></span>
</form>
when file choose for uploadfile3 and press upload file a same page should be reload and then show the string in span lable, I want to connect this web service by android so I tried below code to connect and upload file, the server response 200 code but no file uploads to server and no string shows, it seems that server press upload file without choosing file, what can I do? help please.
public void upLoad2Server() throws ClientProtocolException, IOException {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://11.12.13.174/file_transfer_sample/ClientWebSite/Default.aspx");
File file = new File(Environment.getExternalStorageDirectory().getPath() + "/test.wav");
ContentBody cbFile = new FileBody(file, "audio/wav");
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("FileUpload3", cbFile);
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
Log.i("status", String.valueOf(response.getStatusLine()));
}
Check this code to upload file from Android to Web Server
public class UploadFileToServer extends AsyncTask<Object, String, Object>
{
URL connectURL;
String params;
String responseString;
String fileName;
byte[] dataToServer;
FileInputStream fileInputStream;
private int serverResponseCode;
private String serverResponseMessage;
private static final String TAG = "Uploader";
public void setUrlAndFile(String urlString, File fileName)
{
Log.d(TAG,"StartUploader");
try
{
fileInputStream = new FileInputStream(fileName);
connectURL = new URL(urlString);
}
catch(Exception e)
{
e.getStackTrace();
publishProgress(e.toString());
}
this.fileName = fileName.getAbsolutePath()+".txt";
}
synchronized void doUpload()
{
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
Log.d(TAG,"lv1");
try
{
Log.d(TAG,"doUpload");
publishProgress("Uploading...");
HttpURLConnection conn = (HttpURLConnection)connectURL.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);
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition:form-data; name=\"Uploaded\";filename=\"" + fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
Log.d(TAG,"LvA");
Log.d(TAG,twoHyphens + boundary + lineEnd + ";Content-Disposition:form-data; name=\"Uploaded\";filename=\"" + fileName + "\"" + lineEnd);
int bytesAvailable = fileInputStream.available();
int maxBufferSize = 1024;
int bufferSize = Math.min(bytesAvailable, maxBufferSize);
byte[] buffer = new byte[bufferSize];
int bytesRead = fileInputStream.read(buffer,0, bufferSize);
Log.d(TAG,"LvB");
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();
InputStream is = conn.getInputStream();
int ch;
Log.d(TAG,"LvC");
StringBuffer buff = new StringBuffer();
while((ch=is.read()) != -1)
{
buff.append((char)ch);
}
// publishProgress(buff.toString());
dos.close();
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
serverResponseMessage = conn.getResponseMessage();
// Log.d(TAG,"Buffer "+buff.toString());
Log.d(TAG,"Server Response "+serverResponseMessage);
}
catch(Exception e)
{
e.getStackTrace();
publishProgress(e.toString());
}
}
#Override
protected Object doInBackground(Object... arg0)
{
Log.d(TAG,"lv1a");
doUpload();
Log.d(TAG,"Uploading Completed! Path: "+connectURL);
return null;
}
protected void onProgressUpdate(String... progress)
{
//this.info.setText(progress[0]);
Log.d("Progress", progress[0]);
}
}
Thanks
Check this code.It's upload a file to .NET httphandler server. It uses SSL self-signed security, but it's an example how to use methods, and multipart entity. It works for me.
public static void main(String[] args) throws IOException {
try {
File f = new File(
"c:\\eula.1028.txt");
System.out.println("LENGTH " + f.length());
PostMethod method = new PostMethod("/Handler");
FilePart filePart = new FilePart("file",f);
filePart.setContentType("application/pdf");
Part[] parts = {filePart};
MultipartRequestEntity request = new
MultipartRequestEntity(parts, method.getParams());
method.setRequestEntity(request);
Protocol easyhttps = new Protocol("https",
new EasySSLProtocolSocketFactory(), 2000);
org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient();
client.getHostConfiguration().setHost("localhost", 2000, easyhttps);
client.executeMethod(method);
String s = method.getResponseBodyAsString();
System.out.println(s);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}