مرجع تخصصی برنامه نویسان

بزرگترین انجمن برنامه نویسان فارسی زبان

آموزشگاه برنامه نویسان

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

شنبه, 21 مرداد 1396 15:49

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

با سلام به همه دوستان گرامی.
بنده مبتدی هستم و یک برنامه برای آپلود عکسهام به سرور احتیاج دارم.
این کدهارو از اینترنت گرفتم و تا حدودی ویرایش کردم ولی سرورم هیچی دریافت نمیکنه
به احتمال 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 = "\r\n";
                                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.\n\n See uploaded file here : \n\n"
+ 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;
    }
}

آکادمی برنامه نویسان تلگرام برنامه نویسان
یکشنبه, 22 مرداد 1396 09:09

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

سلام لطفا ارورتون و بگید ؟چی بوده

کسانی که از این پست تشکر کرده اند : msartin,
ﺳﻪ شنبه, 24 مرداد 1396 01:21

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

با تشکر از شما دوست عزیز
برنامم بدون ارور اجرا میشه.

ولی به هر حال به برنامم یک کلاس اضافه کردم که کارمو راه انداخت.
برای همه میزارم شاید به دردشون بخوره :

public int uploadFile(final String selectedFilePath) {
 
    int serverResponseCode = 0;
 
    HttpURLConnection connection;
    DataOutputStream dataOutputStream;
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";
 
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 5 * 1024 * 1024;
    File selectedFile = new File(selectedFilePath);
 
    String[] parts = selectedFilePath.split("/");
    final String fileName = parts[parts.length - 1];
 
    if ( !selectedFile.isFile()) {
 
        runOnUiThread(new Runnable() {
 
            @Override
            public void run() {
                messageText.setText("Source File Doesn't Exist: " + selectedFilePath);
            }
        });
        return 0;
    } else {
        try {
            FileInputStream fileInputStream = new FileInputStream(selectedFile);
            URL url = new URL(upLoadServerUri);
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);//Allow Inputs
            connection.setDoOutput(true);//Allow Outputs
            connection.setUseCaches(false);//Don't use a cached Copy
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setRequestProperty("ENCTYPE", "multipart/form-data");
            connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
            connection.setRequestProperty("uploaded_file", selectedFilePath);
 
            dataOutputStream = new DataOutputStream(connection.getOutputStream());
 
            dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
            dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
                    + selectedFilePath + "\"" + lineEnd);
 
            dataOutputStream.writeBytes(lineEnd);
 
            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            buffer = new byte[bufferSize];
 
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
 
            while (bytesRead > 0) {
                dataOutputStream.write(buffer, 0, bufferSize);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);
            }
 
            dataOutputStream.writeBytes(lineEnd);
            dataOutputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
 
            serverResponseCode = connection.getResponseCode();
            String serverResponseMessage = connection.getResponseMessage();
 
            Log.i(TAG, "Server Response is: " + serverResponseMessage + ": " + serverResponseCode);
 
            if (serverResponseCode == 200) {
                runOnUiThread(new Runnable() {
 
                    @Override
                    public void run() {
                        messageText.setText("File Upload completed.\n\n You can see the uploaded file here: \n\n" + "http://192.168.1.35:8080/download-files/uploads/" + fileName);
                    }
                });
            }
 
            //closing the input and output streams 
            fileInputStream.close();
            dataOutputStream.flush();
            dataOutputStream.close();
 
        }
        catch (FileNotFoundException e) {
            e.printStackTrace();
            runOnUiThread(new Runnable() {
 
                @Override
                public void run() {
                    Toast.makeText(SendpicActivity.this, "File Not Found", Toast.LENGTH_SHORT).show();
                }
            });
        }
        catch (MalformedURLException e) {
            e.printStackTrace();
            Toast.makeText(SendpicActivity.this, "URL error!", Toast.LENGTH_SHORT).show();
 
        }
        catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(SendpicActivity.this, "Cannot Read/Write File!", Toast.LENGTH_SHORT).show();
        }
        return serverResponseCode;
    }
 
}

کسانی که از این پست تشکر کرده اند :

ارسال پاسخ برای این تاپیک

ارسال پاسخ مخصوص اعضا سایت می باشد ! میتوانید با حساب کاربری خود وارد سایت شده یا ثبت نام کنید