سوال در مورد آپلود عکس به سرور

ساخت وبلاگ

با سلام به همه دوستان گرامی.
بنده مبتدی هستم و یک برنامه برای آپلود عکسهام به سرور احتیاج دارم.
این کدهارو از اینترنت گرفتم و تا حدودی ویرایش کردم ولی سرورم هیچی دریافت نمیکنه
به احتمال 90 درصد کدهای اندرویدم مشکل دارن.
اگه دوستان کسی میتونه، لطف کنه کمک کنه، خیلی برام ضروریه.
با تشکر.

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpParams;
import android.app.Activity;
import android.os.Bundle;
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 SendpicActivity extends Activity {

//Declaring views
private Button buttonUpload;
private TextView messageText;
private int serverResponseCode = 0;

String upLoadServerUri = null;

/********** File Path *************/
final String uploadFilePath = G.DIR_APP;
final String uploadFileName = "aval.jpg";

private static DefaultHttpClient mHttpClient;

public static void ServerCommunication() {
HttpParams params = new BasicHttpParams();
params.setParameter(CoreProtocolPNames.PROTOCOL_VE RSION, HttpVersion.HTTP_1_1);
mHttpClient = new DefaultHttpClient(params);
}

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

messageText = (TextView) findViewById(R.id.textView1);
messageText.setText("Uploading file path :- '/mnt/sdcard/" + uploadFileName + "'");

/************* Php script path ****************/
upLoadServerUri = "http://192.168.1.35:8080/download-files/upload.php/";

//Initializing views
buttonUpload = (Button) findViewById(R.id.button1);

//Setting clicklistener
buttonUpload.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {

Thread thread = new Thread(new Runnable() {

@Override
public void run() {

new Thread(new Runnable() {

@Override
public void run() {
runOnUiThread(new Runnable() {

@Override
public void run() {
messageText.setText("uploading started.....");
}
});

HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "rn";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 2 * 1024 * 1024;
File sourceFile = new File(uploadFilePath, uploadFileName);

if ( !sourceFile.isFile()) {

Log.e("uploadFile", "Source File not exist :"
+ uploadFilePath + "/" + uploadFileName);

runOnUiThread(new Runnable() {

@Override
public void run() {
messageText.setText("Source File not exist :"
+ uploadFilePath + "/" + uploadFileName);
}
});

}
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", uploadFileName);

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() {

@Override
public void run() {

String msg = "File Upload Completed.nn See uploaded file here : nn"
+ uploadFileName;

messageText.setText(msg);
Toast.makeText(SendpicActivity.this, "File Upload Complete.",
Toast.LENGTH_SHORT).show();
}
});
} else {
Toast.makeText(SendpicActivity.this, "File Upload Not Complete.",
Toast.LENGTH_SHORT).show();
}

//close the streams //
fileInputStream.close();
dos.flush();
dos.close();

}
catch (MalformedURLException ex) {

ex.printStackTrace();

runOnUiThread(new Runnable() {

@Override
public void run() {
messageText.setText("MalformedURLException Exception : check script url.");
Toast.makeText(SendpicActivity.this, "MalformedURLException",
Toast.LENGTH_SHORT).show();
}
});

Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
}
catch (Exception e) {

e.printStackTrace();

runOnUiThread(new Runnable() {

@Override
public void run() {
messageText.setText("Got Exception : see logcat ");
Toast.makeText(SendpicActivity.this, "Got Exception : see logcat ",
Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server Exception", "Exception : "
+ e.getMessage(), e);
}

} // End else block
}

}).start();
}
});
thread.start();
}

});
}

public void uploadUserPhoto(File image) {

try {

HttpPost httppost = new HttpPost("http://192.168.1.35:8080/download-files/upload.php");

HttpResponse result = mHttpClient.execute(httppost);
InputStream stream;
stream = result.getEntity().getContent();
String resp = inputstreamToString(stream);
Log.i("negano", "response is " + resp);
}
catch (Exception e) {
e.printStackTrace();
}
}

public static String inputstreamToString(InputStream inputStream) {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder builder = new StringBuilder();

try {
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}

return builder.toString();
}
catch (Exception e) {
e.printStackTrace();
}

return null;
}
}

برنامه نویس...
ما را در سایت برنامه نویس دنبال می کنید

برچسب : نویسنده : محمد رضا جوادیان programers بازدید : 145 تاريخ : شنبه 21 مرداد 1396 ساعت: 13:24