简体   繁体   中英

Android HttpUrlConnection uploading files/multipart

So, I'm trying to upload files with a few post commands to my server, however I need a progress bar. When I try to check the progress during my upload it jumps to 100% before it even uploads. Here is my code:

MultipartUtility.java

public class MultipartUtility {

private final String boundary;
private static final String LINE_FEED = "\r\n";
private HttpURLConnection httpConn;
private String charset;
private OutputStream outputStream;
private PrintWriter writer;
private Activity activity;

public MultipartUtility(Activity activity, String requestURL, String charset)throws IOException{
    this.activity = activity;
    this.charset = charset;

    boundary = "==="+System.currentTimeMillis()+"===";

    URL url = new URL(requestURL);
    httpConn = (HttpURLConnection) url.openConnection();
    httpConn.setUseCaches(false);
    httpConn.setDoOutput(true);
    httpConn.setDoInput(true);
    httpConn.setRequestProperty("Content-Type", "multipart/form-data; boundary="+boundary);
    httpConn.setRequestProperty("User-Agent", "CodeJava Agent");
    outputStream = httpConn.getOutputStream();
    writer = new PrintWriter(new OutputStreamWriter(outputStream, charset), true);
}

public void addFormField(String name, String value){
    writer.append("--"+boundary).append(LINE_FEED);
    writer.append("Content-Disposition: form-data; name=\""+name+"\"").append(LINE_FEED);
    writer.append("Content-Type: text/plain; charset="+charset).append(LINE_FEED);
    writer.append(LINE_FEED);
    writer.append(value).append(LINE_FEED);
    writer.flush();
}

public void addFilePart(String fieldName, File uploadFile)throws IOException{
    String fileName = uploadFile.getName();
    writer.append("--"+boundary).append(LINE_FEED);
    writer.append("Content-Disposition: form-data; name=\""+fieldName+"\"; filename=\""+fileName+"\"").append(LINE_FEED);
    writer.append("Content-Type: "+URLConnection.guessContentTypeFromName(fileName)).append(LINE_FEED);
    writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
    writer.append(LINE_FEED);
    writer.flush();




    /*
    final ProgressBar pb = (ProgressBar) activity.findViewById(R.id.progress);
    pb.post(new Runnable(){
        @Override
        public void run(){
            pb.setVisibility(View.VISIBLE);
            //pb.setMax(filesLength);
        }
    });
    */




    FileInputStream inputStream = new FileInputStream(uploadFile);
    byte[] buffer = new byte[4096];
    int bytesRead = -1;

    //long total = 0;
    //int lenghtOfFile = httpConn.getContentLength();
    //long filesLength = uploadFile.length();



    while((bytesRead = inputStream.read(buffer)) != -1){
        outputStream.write(buffer, 0, bytesRead);


        //total += bytesRead;

        //final int progress = (int)((total*100)/filesLength);

        //Log.e("info", progress+"%");


        //pb.setProgress(progress);

    }
    outputStream.flush();
    inputStream.close();

    writer.append(LINE_FEED);
    writer.flush();
}

public void addHeaderField(String name, String value){
    writer.append(name+": "+value).append(LINE_FEED);
    writer.flush();
}

public String finish()throws IOException{
    String response = "";

    writer.append(LINE_FEED).flush();
    writer.append("--"+boundary+"--").append(LINE_FEED);
    writer.close();

    // checks server's status code first
    int status = httpConn.getResponseCode();
    if(status == HttpURLConnection.HTTP_OK){
        BufferedReader reader = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
        String line = null;
        while((line = reader.readLine()) != null){
            response += line;
        }
        reader.close();
        httpConn.disconnect();
    }else{
        throw new IOException("Server returned non-OK status: "+status);
    }

    return response;
}
}

I call it this way:

                    new Thread(new Runnable(){
                    @Override
                    public void run(){
                        try{
                            MultipartUtility multipart = new MultipartUtility(Upload.this, url+"/upvid.php", "UTF-8");

                            multipart.addFormField("name", name.getText().toString());
                            multipart.addFormField("desc", desc.getText().toString());
                            multipart.addFormField("cat", cat.getText().toString());
                            multipart.addFormField("captcha", captcha.getText().toString());

                            multipart.addFilePart("file", file);
                            multipart.addFilePart("file1", file1);

                            final String response = multipart.finish().toString();

                            Log.e("info", response);

                            if(response.equals("<span style='color: #ff0000; font-family: sans-serif'>Please login to post this.</span>")){
                                user = "";
                                ePref.remove("user");
                                ePref.apply();

                                Intent intent = new Intent(Upload.this, Login.class);
                                startActivity(intent);
                                finish();
                                overridePendingTransition(R.anim.dropdown, R.anim.nill);
                            }else{
                                final ProgressBar pb = (ProgressBar) findViewById(R.id.progress);
                                final TextView info = (TextView) findViewById(R.id.info);

                                if(response.startsWith("<span style='color: #aaaaaa; font-family: sans-serif'>Video link: ")){
                                    info.post(new Runnable(){
                                        @Override
                                        public void run(){
                                            pb.setVisibility(View.GONE);
                                            info.setVisibility(View.VISIBLE);
                                            info.setText(Html.fromHtml(response));
                                        }
                                    });
                                }else{
                                    info.post(new Runnable(){
                                        @Override
                                        public void run(){
                                            pb.setVisibility(View.GONE);
                                            info.setVisibility(View.VISIBLE);
                                            info.setText(Html.fromHtml(response));
                                        }
                                    });
                                }

                                submit.post(new Runnable(){
                                    @Override
                                    public void run(){
                                        submit.setEnabled(true);
                                    }
                                });
                            }
                        }catch(Exception e){
                            e.printStackTrace();
                            submit.post(new Runnable(){
                                @Override
                                public void run(){
                                    submit.setEnabled(true);
                                }
                            });
                        }
                    }
                }).start();

All help is appreciated please comment if you have any questions.

Bro, You should use Async Task For API Calling or Data Uploading like this:

initialize progress dialog globally

ProgressDialog progressDialog = new ProgressDialog(EditProjectActivity.this);

 class  DataUpload extends AsyncTask<Void,Void,Void>
    {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
// when this method is called the progress is start 
            progressDialog.setMessage("please wait");
            progressDialog.show();

        }

        @Override
        protected Void doInBackground(Void... voids) {


// call your multipart http 

try{
                            MultipartUtility multipart = new MultipartUtility(Upload.this, url+"/upvid.php", "UTF-8");

                            multipart.addFormField("name", name.getText().toString());
                            multipart.addFormField("desc", desc.getText().toString());
                            multipart.addFormField("cat", cat.getText().toString());
                            multipart.addFormField("captcha", captcha.getText().toString());

                            multipart.addFilePart("file", file);
                            multipart.addFilePart("file1", file1);

                            final String response = multipart.finish().toString();

                            Log.e("info", response);

                            if(response.equals("<span style='color: #ff0000; font-family: sans-serif'>Please login to post this.</span>")){
                                user = "";
                                ePref.remove("user");
                                ePref.apply();

                                Intent intent = new Intent(Upload.this, Login.class);
                                startActivity(intent);
                                finish();
                                overridePendingTransition(R.anim.dropdown, R.anim.nill);
                            }else{
                                final ProgressBar pb = (ProgressBar) findViewById(R.id.progress);
                                final TextView info = (TextView) findViewById(R.id.info);

                                if(response.startsWith("<span style='color: #aaaaaa; font-family: sans-serif'>Video link: ")){
                                    info.post(new Runnable(){
                                        @Override
                                        public void run(){
                                            pb.setVisibility(View.GONE);
                                            info.setVisibility(View.VISIBLE);
                                            info.setText(Html.fromHtml(response));
                                        }
                                    });
                                }else{
                                    info.post(new Runnable(){
                                        @Override
                                        public void run(){
                                            pb.setVisibility(View.GONE);
                                            info.setVisibility(View.VISIBLE);
                                            info.setText(Html.fromHtml(response));
                                        }
                                    });
                                }

                                submit.post(new Runnable(){
                                    @Override
                                    public void run(){
                                        submit.setEnabled(true);
                                    }
                                });
                            }
                        }catch(Exception e){
                            e.printStackTrace();
                            submit.post(new Runnable(){
                                @Override
                                public void run(){
                                    submit.setEnabled(true);
                                }


            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);

 progressDialog.dismiss();
// when method complete its job the progress stopp
        }
    }

now to call that method use :

DataUpload dataup = new DataUpload(this); dataup.execute();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM