Android HttpUrlConnection上传文件/ multipart

时间:2018-05-05 02:14:30

标签: java android file upload httpurlconnection

所以,我试图将带有一些post命令的文件上传到我的服务器,但是我需要一个进度条。当我尝试在上传过程中检查进度时,它会在上传之前跳至100%。这是我的代码:

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;
}
}

我这样称呼它:

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

如果您有任何疑问,请提供所有帮助。

1 个答案:

答案 0 :(得分:0)

兄弟, 您应该使用异步任务进行API调用或数据上传,如下所示:

  

全局初始化进度对话框

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
        }
    }

现在调用该方法使用:

  

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