Android Update file to php serve - android

I am trying to upload image to php server. But it gives me
java.io.FileNotFoundException: http://*******.info/test.php
how can I solve this problem?
package com.androidexample.uploadtoserver;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class UploadToServer extends Activity {
TextView messageText;
Button uploadButton;
int serverResponseCode = 0;
ProgressDialog dialog = null;
String upLoadServerUri = null;
/********** File Path *************/
final String uploadFilePath = "/mnt/sdcard/";
final String uploadFileName = "service.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);
uploadButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog = ProgressDialog.show(UploadToServer.this, "", "Uploading file...", true);
new Thread(new Runnable() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
//messageText.setText("uploading started.....");
}
});
doFileUpload();
Log.d("deneme", "buraya geldim i");
}
}).start();
}
});
}
private void doFileUpload() {
HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
String existingFileName = uploadFilePath+uploadFileName;
// imageView1.setImageURI(Uri.parse(existingFileName));
Log.e("--adress Debug--",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://w.****.info/test.php";
Log.d("deneme1", "buraya geldim i");
try {
//------------------ CLIENT REQUEST
FileInputStream fileInputStream = new FileInputStream(new File(existingFileName));
// open a URL connection to the Servlet
URL url = new URL(urlString);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
// Allow Inputs
conn.setDoInput(true);
// Allow Outputs
conn.setDoOutput(true);
// Don't use a cached copy.
conn.setUseCaches(false);
// Use a post method.
Log.d("deneme2", "buraya geldim i");
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
Log.d("deneme3", "buraya geldim i");
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);
Log.e("--burya geldimi --","");
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
Log.e("--b----------------mi --","");
}
Log.d("deneme4", "buraya geldim i");
// 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("Debug0", "error1: " + ex.getMessage(), ex);
} catch (IOException ioe) {
Log.e("Debug1", "error2: " + ioe.getMessage(), ioe);
}
//------------------ read the SERVER RESPONSE
try {
inStream = new DataInputStream(conn.getInputStream());
String str;
while ((str = inStream.readLine()) != null) {
Log.e("Debug2", "Server Response " + str);
}
inStream.close();
} catch (IOException ioex) {
Log.e("Debug3", "error3: " + ioex.getMessage(), ioex);
}
}
}
}
}
my cat log
12-15 21:10:33.599: E/Debug3(9087): error3: http://***.info/test.php
12-15 21:10:33.599: E/Debug3(9087): java.io.FileNotFoundException: http://****.info/test.php
12-15 21:10:33.599: E/Debug3(9087): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:521)
12-15 21:10:33.599: E/Debug3(9087): at com.androidexample.uploadtoserver.UploadToServer.doFileUpload(UploadToServer.java:140)
12-15 21:10:33.599: E/Debug3(9087): at com.androidexample.uploadtoserver.UploadToServer.access$0(UploadToServer.java:66)
12-15 21:10:33.599: E/Debug3(9087): at com.androidexample.uploadtoserver.UploadToServer$1$1.run(UploadToServer.java:57)
12-15 21:10:33.599: E/Debug3(9087): at java.lang.Thread.run(Thread.java:1019)

this is my server site code
<?php
$file_path = "uploads/";
$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";
}
?>

Related

Audio File Upload to a Live Server in android

While I try to run the below code it doesn't show any error . its logs "File Witten ". but the file is not uploaded in the server. while I try the same code in locally with PHP code is able to upload. plz help .thanks in advance
package com.example.file_upload_demo;
import android.os.Handler;
import android.os.Message;enter code here
import android.util.Log;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class FileUploadUtility {
static String SERVER_PATH = "example.com";
enter code here
public static void doFileUpload(final String selectedPath, final Handler handler) {
//
new Thread(new Runnable() {
#Override
public void run() {`enter code here`
HttpsTrustManager.allowAllSSL();
HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
String lineEnd = "rn";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
String responseFromServer = "";
try {
//------------------ CLIENT REQUEST
FileInputStream fileInputStream = new FileInputStream(new File(selectedPath));
// open a URL connection to the Servlet
URL url = new URL(SERVER_PATH);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
// Allow Inputs
conn.setDoInput(true);
// Allow Outputs
conn.setDoOutput(true);
// Don't use a cached copy.
conn.setUseCaches(false);
// Use a post method.
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "application/json;charset=" + boundary);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"mp3File\";filename=\""
+ selectedPath + "\"" + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// close streams
Log.e("Debug", "File is written");
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
Log.e("Debug", "error: " + ex.getMessage(), ex);
sendMessageBack(responseFromServer, 0, handler);
return;
} catch (IOException ioe) {
Log.e("Debug", "error: " + ioe.getMessage(), ioe);
sendMessageBack(responseFromServer, 0, handler);
return;
}
responseFromServer = processResponse(conn, responseFromServer);
sendMessageBack(responseFromServer, 1, handler);
}
}).start();
}
private static String processResponse(HttpURLConnection conn, String responseFromServer) {
DataInputStream inStream;
try {
inStream = new DataInputStream(conn.getInputStream());
String str;
while ((str = inStream.readLine()) != null) {
responseFromServer = str;
}
inStream.close();
} catch (IOException ioex) {
Log.e("Debug", "error: " + ioex.getMessage(), ioex);
}
return responseFromServer;
}
static void sendMessageBack(String responseFromServer, int success, Handler handler) {
Message message = new Message();
message.obj = responseFromServer;
message.arg1 = success;
handler.sendMessage(message);
}`enter code here`
}
Try this:
1) open manifests folder in you app
2) add
<uses-permission android:name="android.permission.INTERNET" />
3) add <uses-permission android:name="android.permission.MANAGE_DOCUMENTS" />

How can send images from Android Application to Server?

I want to store images in a server via POST, the images that are sent are sent from the local storage cell, this my code asynchronous class in Android :
class ImageUpload extends AsyncTask<Void, Void, String>{
#Override
protected String doInBackground(Void... var) {
System.out.println(incidentId);
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
InputStream inputStream = null;
String twoHyphens = "--";
String boundary = "*****" + Long.toString(System.currentTimeMillis()) + "*****";
String lineEnd = "\r\n";
String result = "";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
String[] q = mCurrentPhotoPath.split("/");
int idx = q.length - 1;
try {
File file = new File(mCurrentPhotoPath);
FileInputStream fileInputStream = new FileInputStream(file);
URL url = new URL(url_add_attachment);
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "multipart/form-data; charset=UTF-8");
connection.setRequestProperty("Accept", "application/json");
outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes(twoHyphens + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"" + "file" + "\"; filename=\"" + q[idx] + "\"" + lineEnd);
outputStream.writeBytes("Content-Type: " + "image" + lineEnd);
outputStream.writeBytes("Content-Transfer-Encoding: binary" + lineEnd);
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
outputStream.writeBytes(lineEnd);
try {
outputStream.writeBytes(twoHyphens + lineEnd);
//outputStream.writeBytes("Content-Disposition: form-data; name=\"" + key + "\"" + lineEnd);
outputStream.writeBytes("Content-Type: text/plain" + lineEnd);
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(lineEnd);
//}
outputStream.writeBytes(twoHyphens + twoHyphens + lineEnd);
} catch (Exception e) {
e.printStackTrace();
}
int status = connection.getResponseCode();
InputStream in;
if(status >= HttpStatus.SC_BAD_REQUEST)
in = connection.getErrorStream();
else
in = connection.getInputStream();
inputStream = connection.getInputStream();
result = convertStreamToString(in);
fileInputStream.close();
inputStream.close();
outputStream.flush();
outputStream.close();
}catch(Exception e){
e.printStackTrace();
}
return result;
}
}
The server throws 400 error response also send me the exception :
java.io.FileNotFoundException: http://10.0.2.2/app_dev.php/incidents/8/attachments
MainActivity.java
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener{
private TextView messageText;
private Button uploadButton, btnselectpic;
private ImageView imageview;
private int serverResponseCode = 0;
private ProgressDialog dialog = null;
private String upLoadServerUri = null;
private String imagepath=null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
uploadButton = (Button)findViewById(R.id.uploadButton);
btnselectpic = (Button)findViewById(R.id.button_selectpic);
messageText = (TextView)findViewById(R.id.messageText);
imageview = (ImageView)findViewById(R.id.imageView_pic);
btnselectpic.setOnClickListener(this);
uploadButton.setOnClickListener(this);
upLoadServerUri = "http://10.0.2.2/uploads/UploadToServer.php";
ImageView img= new ImageView(this);
}
#Override
public void onClick(View arg0) {
if(arg0==btnselectpic)
{
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), 1);
}
else if (arg0==uploadButton) {
dialog = ProgressDialog.show(MainActivity.this, "", "Uploading file...", true);
messageText.setText("uploading started.....");
new Thread(new Runnable() {
public void run() {
uploadFile(imagepath);
}
}).start();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1 && resultCode == RESULT_OK) {
//Bitmap photo = (Bitmap) data.getData().getPath();
Uri selectedImageUri = data.getData();
imagepath = getPath(selectedImageUri);
Bitmap bitmap=BitmapFactory.decodeFile(imagepath);
imageview.setImageBitmap(bitmap);
messageText.setText("Uploading file path:" +imagepath);
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
public int uploadFile(String sourceFileUri) {
String fileName = sourceFileUri;
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File(sourceFileUri);
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
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(upLoadServerUri);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("uploaded_file", fileName);
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);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
if(serverResponseCode == 200){
runOnUiThread(new Runnable() {
public void run() {
String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
+" F:/wamp/wamp/www/uploads";
messageText.setText(msg);
Toast.makeText(MainActivity.this, "File Upload Complete.", Toast.LENGTH_SHORT).show();
}
});
}
//close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} 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;
} // End else block
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<ImageView
android:id="#+id/imageView_pic"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="center"
android:src="#drawable/ic_launcher" />
<Button
android:id="#+id/button_selectpic"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Select Picture" />
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Click To Upload File"
android:id="#+id/uploadButton"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text=""
android:id="#+id/messageText"
android:textColor="#000000"
android:textStyle="bold"
/>
</LinearLayout>
Mainfest file::
<uses-permission android:name="android.permission.INTERNET"/>
UploadToServer.php
<?php
$file_path = "../image upload folder name here/";
$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";
}
?>
You can pass your server url in following method to upload any file.Change file parameter in given code with your actual file.
public static HttpResponse uploadFile(String url) throws ClientProtocolException, IOException {
try {
// the file to be posted
String textFile = Environment.getExternalStorageDirectory() + "/file.txt";
// /.v(TAG, "textFile: " + textFile);
// Log.v(TAG, "postURL: " + url);
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is
// established.
// The default value is zero, that means the timeout is not used.
int timeoutConnection = 10000;
// HttpConnectionParams.setConnectionTimeout(httpParameters,
// timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 5000;
// HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
HttpClient httpClient = new DefaultHttpClient(httpParameters);
// post header
HttpPost httpPost = new HttpPost(url);
File file = new File(textFile);
FileBody fileBody = new FileBody(file);
MultipartEntityBuilder mBuilder = MultipartEntityBuilder.create();
mBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
mBuilder.addPart("fileUpload", fileBody);
httpPost.setEntity(mBuilder.build());
return httpClient.execute(httpPost);
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

Android - File upload works on localhost using Xampp but does not work on server

I have made an app that is supposed to let me upload to a server but it only works on localhost. The online server I am using is ueuo.com (free). What might be a solution to this? Funny thing though, the server response code I get is 200.
Here is the app:
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
private static final String JPEG_FILE_PREFIX = "img";
private static final String JPEG_FILE_SUFFIX = ".jpg";
private static final String FOLDER_NAME = "/idms/";
private String imageFileName = "";
Button btnUpload;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
makeDirectory();
btnUpload = (Button) findViewById(R.id.button1);
btnUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss")
.format(new Date());
imageFileName = JPEG_FILE_PREFIX + timeStamp + JPEG_FILE_SUFFIX;
File file = new File(Environment.getExternalStorageDirectory()
.getPath() + FOLDER_NAME + imageFileName);
Uri imageUri = Uri.fromFile(file);
Intent intent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, 0);
}
});
}
public void makeDirectory() {
File dir = new File(Environment.getExternalStorageDirectory()
+ FOLDER_NAME);
if (!dir.exists()) {
dir.mkdir();
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//String pathToOurFile = Environment.getExternalStorageDirectory()
.getPath() + FOLDER_NAME + imageFileName;
// Upload the image to the server
new Thread(new Runnable() {
public void run() {
uploadFile();
}
}).start();
}
protected void uploadFile() {
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
// DataInputStream inputStream = null;
String pathToOurFile = Environment.getExternalStorageDirectory()
.getPath() + FOLDER_NAME + imageFileName;
String urlServer = "http://idmstest.ueuo.com/upload_api/uploadtoserver.php";
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
Log.d("tester", pathToOurFile);
try {
FileInputStream fileInputStream = new FileInputStream(new File(
pathToOurFile));
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)
#SuppressWarnings("unused")
int serverResponseCode = connection.getResponseCode();
#SuppressWarnings("unused")
String serverResponseMessage = connection.getResponseMessage();
Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
fileInputStream.close();
outputStream.flush();
outputStream.close();
Log.d("tester", pathToOurFile);
} catch (Exception ex) {
// Exception handling
ex.printStackTrace();
Log.e("Upload file to server Exception", "Exception : "
+ ex.getMessage(), ex);
}
}
Here is the server-side php:
<?php
$file_path = "uploads/";
$file_path = $file_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $file_path)) {
echo "success";
} else{
echo "fail";
}
?>

Error when uploading image from gallery to server

I am getting a error when I try to run my application. I can start my application and pick the image but then the application crash. I really don't know what is wrong ?
The error message is as below:
11-15 12:32:44.167: E/AndroidRuntime(24617): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=2, result=-1, data=Intent { dat=content://media/external/images/media/328 flg=0x1 }} to activity {com.example.testuploade4/com.example.testuploade4.MainActivity}: android.os.NetworkOnMainThreadException
Here is my android class:
package com.example.testuploade4;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.Toast;
public class MainActivity extends Activity {
private static final int SELECT_IMAGE = 1;
String selectedPath;
String urlString = "http://jadder.dk/sjov/uploade1.php";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
openGallery();
}
public void openGallery() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Image "),
SELECT_IMAGE);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_IMAGE) {
System.out.println("SELECT_IMAGE");
Uri selectedImageUri = data.getData();
selectedPath = getPath(selectedImageUri);
System.out.println("SELECT_IMAGE Path : " + selectedPath);
doFileUpload();
}
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
private void doFileUpload() {
HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
String lineEnd = "rn";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
String responseFromServer = "";
try {
// ------------------ CLIENT REQUEST
FileInputStream fileInputStream = new FileInputStream(new File(
selectedPath));
// open a URL connection to the Servlet
URL url = new URL(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=\"uploaded_file\";filename=\""
+ selectedPath + "\"" + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// close streams
Log.e("Debug", "File is written");
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
Log.e("Debug", "error: " + ex.getMessage(), ex);
} catch (IOException ioe) {
Log.e("Debug", "error: " + ioe.getMessage(), ioe);
}
// ------------------ read the SERVER RESPONSE
try {
inStream = new DataInputStream(conn.getInputStream());
String str;
while ((str = inStream.readLine()) != null) {
Log.e("Debug", "Server Response " + str);
}
inStream.close();
} catch (IOException ioex) {
Log.e("Debug", "error: " + ioex.getMessage(), ioex);
}
}
}
Here is my php code:
<?php
// Where the file is going to be placed
$target_path = "uploads/";
/* Add the original filename to our target path.
Result is "uploads/filename.extension" */
$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!";
echo "filename: " . basename( $_FILES['uploadedfile']['name']);
echo "target_path: " .$target_path;
}
?>
Now i am getting a new error. I Think ther problem is in the php code but i i dont know:
The errror message is:
File is written
Server Response
There was an error uploading the file, please try again!filename: target_path: uploads/
EDIT:
package com.example.testuploade4;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.Toast;
public class MainActivity extends Activity {
private static final int SELECT_IMAGE = 1;
String selectedPath;
String urlString = "http://jadder.dk/sjov/uploade1.php";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
openGallery();
}
public void openGallery() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Image "),
SELECT_IMAGE);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_IMAGE) {
System.out.println("SELECT_IMAGE");
Uri selectedImageUri = data.getData();
selectedPath = getPath(selectedImageUri);
System.out.println("SELECT_IMAGE Path : " + selectedPath);
doFileUpload();
}
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
private void doFileUpload() {
new AsyncTask<Void, Void, Void>() {
protected Void doInBackground(Void... arg0) {
HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
String lineEnd = "rn";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
String responseFromServer = "";
try {
// ------------------ CLIENT REQUEST
FileInputStream fileInputStream = new FileInputStream(new File(selectedPath));
// open a URL connection to the Servlet
URL url = new URL(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=\"uploaded_file\";filename=\"" + selectedPath + "\"" + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// close streams
Log.e("Debug", "File is written");
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
Log.e("Debug", "error: " + ex.getMessage(), ex);
} catch (IOException ioe) {
Log.e("Debug", "error: " + ioe.getMessage(), ioe);
}
// ------------------ read the SERVER RESPONSE
try {
inStream = new DataInputStream(conn.getInputStream());
String str;
while ((str = inStream.readLine()) != null) {
Log.e("Debug", "Server Response " + str);
}
inStream.close();
} catch (IOException ioex) {
Log.e("Debug", "error: " + ioex.getMessage(), ioex);
}
return null;
}
}.execute();
}
}
The Logcat:
11-15 13:30:16.211: D/libEGL(26221): loaded /system/lib/egl/libEGL_adreno200.so
11-15 13:30:16.211: D/libEGL(26221): loaded /system/lib/egl/libGLESv1_CM_adreno200.so
11-15 13:30:16.211: D/libEGL(26221): loaded /system/lib/egl/libGLESv2_adreno200.so
11-15 13:30:16.221: I/Adreno200-EGL(26221): <qeglDrvAPI_eglInitialize:265>: EGL 1.4 QUALCOMM Build: Iabe52cfaeae4c5fab1acacfe6f056ba15fa93274
11-15 13:30:16.251: D/OpenGLRenderer(26221): Enabling debug mode 0
11-15 13:30:16.351: D/dalvikvm(26221): GC_FOR_ALLOC freed 104K, 2% free 9228K/9376K, paused 15ms, total 16ms
11-15 13:30:20.454: I/System.out(26221): SELECT_IMAGE
11-15 13:30:20.465: I/System.out(26221): SELECT_IMAGE Path : /storage/emulated/0/Download/560843_531646073574745_683776063_n.jpg
11-15 13:30:20.575: D/dalvikvm(26221): GC_FOR_ALLOC freed 103K, 2% free 9574K/9756K, paused 20ms, total 20ms
11-15 13:30:20.595: E/Debug(26221): File is written
11-15 13:30:21.275: E/Debug(26221): Server Response There was an error uploading the file, please try again!filename: target_path: uploads/
Youur doFileUpload() method is running in MainThread, which should run in background.
Try following way,
runOnUiThread(new Runnable(){
public void run() {
doFileUpload()
}
});
You must upload file in asynctask like this
private void doFileUpload() {
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... arg0) {
HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
String lineEnd = "rn";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
String responseFromServer = "";
try {
// ------------------ CLIENT REQUEST
FileInputStream fileInputStream = new FileInputStream(new File(selectedPath));
// open a URL connection to the Servlet
URL url = new URL(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\";name=\"" + selectedPath + "\"" + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// close streams
Log.e("Debug", "File is written");
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
Log.e("Debug", "error: " + ex.getMessage(), ex);
} catch (IOException ioe) {
Log.e("Debug", "error: " + ioe.getMessage(), ioe);
}
// ------------------ read the SERVER RESPONSE
try {
inStream = new DataInputStream(conn.getInputStream());
String str;
while ((str = inStream.readLine()) != null) {
Log.e("Debug", "Server Response " + str);
}
inStream.close();
} catch (IOException ioex) {
Log.e("Debug", "error: " + ioex.getMessage(), ioex);
}
return null;
}
}.execute();
}

Android upload file to .NET web server

I want to write an android app that can upload a file to a c sharp base web server.
So far I have no luck. I kept getting Address family not supported by protocol.
I've added INTERNET and WRITE_EXTERNAL_STORAGE in my manifest file.
Keep in mind that I run this in emulator.
Any idea or suggestion is really appreciated.
Thank you in advance
Justin The
anyway here is my code
Android - Uploader.java
package com.main;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.TextView;
public class Uploader extends AsyncTask<Object, String, Object>
{
URL connectURL;
String params;
String responseString;
String fileName;
byte[] dataToServer;
FileInputStream fileInputStream;
TextView info;
private static final String TAG = "Uploader";
void setUrlAndFile(String urlString, String fileName, TextView info)
{
Log.d(TAG,"StartUploader");
this.info = info;
try
{
fileInputStream = new FileInputStream(fileName);
connectURL = new URL(urlString);
}
catch(Exception e)
{
publishProgress(e.toString());
}
this.fileName = fileName;
}
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=\"uploadedfile\";filename=\"" + fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
Log.d(TAG,"LvA");
Log.d(TAG,twoHyphens + boundary + lineEnd + ";Content-Disposition:form-data; name=\"uploadedfile\";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();
Log.d(TAG,"lv2");
}
catch(Exception e)
{
publishProgress(e.toString());
}
}
#Override
protected Object doInBackground(Object... arg0)
{
Log.d(TAG,"lv1a");
doUpload();
Log.d(TAG,"lv1b");
return null;
}
protected void onProgressUpdate(String... progress)
{
this.info.setText(progress[0]);
}
}
and this is the main activity
package com.main;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FilePermission;
import java.io.OutputStreamWriter;
import java.net.SocketException;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;
public class ReadWriteToPCActivity extends Activity
{
private static final String TAG = "ReadWriteToPCActivity";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
View upload = findViewById(R.id.Upload);
final EditText path = (EditText)findViewById(R.id.Path);
final TextView info = (TextView)findViewById(R.id.Info);
Log.d(TAG,"Start");
File fn = new File(Environment.getExternalStorageDirectory()+"/new.xml");
upload.setOnClickListener
(
new OnClickListener()
{
public void onClick(View v)
{
try
{
Log.d(TAG,"Step1");
WriteFile();
Uploader uploader = new Uploader();
//uploader.setUrlAndFile("http://192.168.0.123/receiver.aspx", path.getText().toString(), info);
uploader.setUrlAndFile("http://192.168.0.123/personalfinance/receiver.aspx", Environment.getExternalStorageDirectory()+"/samplefile.txt", info);
//uploader.setUrlAndFile("http://10.0.2.2/personalfinance/receiver.aspx", Environment.getExternalStorageDirectory()+"/new.xml", info);
//uploader.setUrlAndFile("http://192.168.0.123/personalfinance/ReceiveUpload.aspx", Environment.getExternalStorageDirectory()+"/new.xml", info);
Log.d(TAG,"Upload." + Environment.getExternalStorageDirectory()+"/samplefile.txt;" + info.getText().toString());
uploader.execute();
}
catch(Exception e)
{
path.setText(e.toString());
Log.d(TAG,e.toString());
}
}
private void WriteFile()
{
try
{
Log.d(TAG,"Step 1 write file");
File newfile = new File(Environment.getExternalStorageDirectory() + "/samplefile.txt");
Log.d(TAG,"Step 2 write file");
if(!newfile.exists() && !newfile.createNewFile())
{
Log.d(TAG,"File exists");
}
Log.d(TAG,"cp3");
newfile.createNewFile();
Log.d(TAG,"Step 3 write file");
FileOutputStream fos = null;
Log.d(TAG,"Step 4 write file");
fos = new FileOutputStream(newfile);
Log.d(TAG,"Step 5 write file");
OutputStreamWriter osw = new OutputStreamWriter(fos);
osw.write("Hello Android");
osw.flush();
osw.close();
FilePermission fp;
fp = new FilePermission(Environment.getExternalStorageDirectory()+"/samplefile.txt","read");
Log.d(TAG,"File created");
}
catch(Exception e)
{
Log.d(TAG,e.toString());
}
}
}
);
}
}
and last, this is my receiver file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace PersonalFinance
{
public partial class receiver : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
HttpFileCollection uploadFiles = Request.Files;
HttpPostedFile postedFile = uploadFiles[0];
System.IO.Stream inStream = postedFile.InputStream;
byte[] fileData = new byte[postedFile.ContentLength];
inStream.Read(fileData, 0, postedFile.ContentLength);
postedFile.SaveAs(Server.MapPath("Data") + "\\" + postedFile.FileName);
}
}
}

Categories

Resources