Android文件上传无效

时间:2016-10-19 09:49:44

标签: android post android-file

我开发了一个应用程序来从手机上传任何文件。当我单击选择按钮时,它会显示电话目录。当我选择要上传到我的服务器的图像时,它不会上传文件。但它运行没有错误。你知道怎么解决这个问题吗?

public class MainActivity extends AppCompatActivity {

private TextView txtPercentage;
private ProgressBar progressBar;

File sourceFile;


String filepath;
String imagepath;

TextView messageText;
Button uploadButton;
Button selectButton;
int serverResponseCode = 0;
ProgressDialog dialog = null;

String upLoadServerUri = null;

/**********  File Path *************/
final String uploadFilePath = Environment.getExternalStorageDirectory().getPath() + "/";
final String uploadFileName = "gt.png";

Uri selectedFileUri = null;

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

    txtPercentage = (TextView) findViewById(R.id.txtPercentage);

    progressBar = (ProgressBar) findViewById(R.id.progressBar);

    uploadButton = (Button) findViewById(R.id.uploadButton);
    selectButton = (Button) findViewById(R.id.selectButton);
    messageText = (TextView) findViewById(R.id.messageText);



    messageText.setText("Uploading file path :- " + Environment.getExternalStorageDirectory().getPath() + "/"+ uploadFileName);

    /************* Php script path ****************/
    upLoadServerUri = "http://192.168.1.3/work/filesharing/2.php";

    selectButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent intent = new Intent();
            //dialog = ProgressDialog.show(MainActivity.this, "", "Uploading file...", true);

            intent.setType("*/*"); // intent.setType("video/*"); to select videos to upload
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent, "Select File"), 1);
        }
    });
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
    if (requestCode == 1 && resultCode == RESULT_OK) {


        selectedFileUri = data.getData();

        InputStream is = null;
        try {
            is = getContentResolver().openInputStream(selectedFileUri);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        new ProcessFileUploadTask(new File(selectedFileUri.getPath()));

       Uri uri = data.getData();
        File myFile = new File(uri.getPath());
    } else {

    }
}

public int uploadFile(String myFile) throws FileNotFoundException {

    Log.d("LOGTAG", "Output21 :" );
    String fileName = myFile;

    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(myFile);

    sourceFile = new File(myFile);

    if (!sourceFile.isFile()) {

        dialog.dismiss();

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

        runOnUiThread(new Runnable() {
            public void run() {
                messageText.setText("Source File not exist :"
                        +uploadFilePath + "" + uploadFileName);
            }
        });
        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";

                        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("LOGTAG","Upload file to server Exception" + "Exception : " + e.getMessage(), e);
        }
        dialog.dismiss();
        return serverResponseCode;

    } // End else block
}

//asynch task to upload file with parameters
public class ProcessFileUploadTask extends AsyncTask<Void, Integer, Void>  implements DialogInterface.OnCancelListener{

    private ProgressDialog progressDialog;
    private File file;
    String res="";

    public ProcessFileUploadTask(File file) {
        this.file = file;
    }

    @Override
    // can use UI thread here
    protected void onPreExecute() {
        super.onPreExecute();
        try{
            progressDialog = new ProgressDialog(MainActivity.this);
            progressDialog.setMessage("Uploading... Please wait!");
            progressDialog.setIndeterminate(false);
            progressDialog.setMax(100);
            progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            progressDialog.setCancelable(false);
            progressDialog.setCanceledOnTouchOutside(false);
            progressDialog.show();
        }
        catch(Exception e){
            Log.e("Exception:",e.toString());
        }
    }

    protected void onPostExecute(Void v) {

        progressDialog.dismiss();
        Toast toast=Toast.makeText(getApplicationContext(), "Uploaded Successfully.", Toast.LENGTH_LONG);

    }

    @Override
    protected Void doInBackground(Void... v) {
        HttpURLConnection.setFollowRedirects(false);
        HttpURLConnection conn = null;


        try {
            //posting parameters with url
            String finalUrl = Uri.parse(upLoadServerUri)
                    .buildUpon()
                    .appendQueryParameter("name", "firzan")
                    .build().toString();
            conn = (HttpURLConnection) new URL(finalUrl).openConnection();
            conn.setConnectTimeout(10*1000);

            conn.setRequestMethod("POST");
            String boundary = "---------------------------boundary";
            String tail = "\r\n--" + boundary + "--\r\n";
            conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
            conn.setDoOutput(true);

            String metadataPart = "--" + boundary + "\r\n"
                    + "Content-Disposition: form-data; name=\"metadata\"\r\n\r\n"
                    + "" + "\r\n";

            String fileHeader1 = "--" + boundary + "\r\n"
                    + "Content-Disposition: form-data; name=\"uploaded_file\"; filename=\""
                    + "serverFileName" + "\"\r\n"
                    + "Content-Type: application/octet-stream\r\n"
                    + "Content-Transfer-Encoding: binary\r\n";

            long fileLength = file.length() + tail.length();
            String fileHeader2 = "Content-length: " + fileLength + "\r\n";
            String fileHeader = fileHeader1 + fileHeader2 + "\r\n";
            String stringData = metadataPart + fileHeader;

            long requestLength = stringData.length() + fileLength;
            conn.setRequestProperty("Content-length", "" + requestLength);
            conn.setFixedLengthStreamingMode((int) requestLength);
            conn.connect();

            DataOutputStream out = new DataOutputStream(conn.getOutputStream());
            out.writeBytes(stringData);
            out.flush();

            int progress = 0;
            int bytesRead = 0;
            byte buf[] = new byte[10*1024];
            BufferedInputStream bufInput = new BufferedInputStream(new FileInputStream(file));
            while ((bytesRead = bufInput.read(buf)) != -1) {

                // write output
                out.write(buf, 0, bytesRead);
                out.flush();
                progress += bytesRead;
                // update progress bar
                publishProgress(progress);
            }

            // Write closing boundary and close stream
            out.writeBytes(tail);
            out.flush();
            out.close();

            // Get server response
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line = "";
            StringBuilder builder = new StringBuilder();
            while((line = reader.readLine()) != null) {
                builder.append(line);
            }
            serverResponseCode = conn.getResponseCode();
            //serverResponseMessage = conn.getResponseMessage();
            //ServerResponce=builder.toString();
            //Log.e("ser res",ServerResponce.toString());
        }
        catch (Exception e) {
            Log.e("Exception",e.toString());
            progressDialog.dismiss();
            //exceptionText=e.toString();

        } finally {
            if (conn != null) conn.disconnect();
            //finish();
        }

        return null;
    }
    @Override
    protected void onProgressUpdate(Integer... progress) {
        progressDialog.setProgress((int) (progress[0]));
    }
    @Override
    public void onCancel(DialogInterface dialog) {
        super.onCancelled();
        cancel(true);
        dialog.dismiss();
        finish();

    }

}

0 个答案:

没有答案