如何在android中使用mulipartentity上传图片?

时间:2018-04-09 05:21:38

标签: java android

我正在使用带有MultipartEntity的asynktask进行文件上传,我从服务器端获得了成功MSG,但我的图像没有上传到服务器,即使我得到成功响应任何帮助,我在互联网上搜索我无法得到任何相关回答我的代码是:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.resume_upload_activity);
    ivAttachment = (ImageView) findViewById(R.id.ivAttachment);
    bUpload = (Button) findViewById(R.id.b_upload);
    tvFileName = (TextView) findViewById(R.id.tv_file_name);
    ivAttachment.setOnClickListener(this);
    bUpload.setOnClickListener(this);
}

@Override
public void onClick(View v) {
    if(v== ivAttachment){

        //on attachment icon click
        showFileChooser();
    }
    if(v== bUpload){

        //on upload button Click
        if(selectedFilePath != null){
            new  UploadImageTask().execute();
        }else
        {
            Toast.makeText(getApplicationContext(),"Please choose a File First",Toast.LENGTH_SHORT).show();
        }

    }
}

private void showFileChooser() {
    Intent intent = new Intent();
    //sets the select file to all types of files
    intent.setType("image/*");
    //allows to select data and return it
    intent.setAction(Intent.ACTION_GET_CONTENT);
    //starts new activity to select file and return data
    startActivityForResult(Intent.createChooser(intent,"Choose File to Upload.."),PICK_FILE_REQUEST);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(resultCode == RESULT_OK){
        if(requestCode == PICK_FILE_REQUEST){
            if(data == null){
                //no data present
                return;
            }


            Uri selectedFileUri = data.getData();
            try {
                selectedFilePath = FilePath.getPath(this,selectedFileUri);
            } catch (Exception e) {
                e.printStackTrace();
            }
            Log.i(TAG,"Selected File Path:" + selectedFilePath);

            if(selectedFilePath != null && !selectedFilePath.equals("")){
                tvFileName.setText(selectedFilePath);
            }else{
                Toast.makeText(this,"Cannot upload file to server",Toast.LENGTH_SHORT).show();
            }
        }
    }
}




private class UploadImageTask extends AsyncTask<Void, Void, String> {

    private ProgressDialog dialog = new ProgressDialog(FileUpload.this);
    ByteArrayBody bab;
    String response;

    @Override
    protected void onPreExecute()
    {
        dialog.setTitle("Uploading Image");
        dialog.setMessage("Processing...");
        dialog.setCancelable(true);
        dialog.show();
    }

    @Override
    protected String doInBackground(Void... params) {

        try {

            URL url = new URL(SERVER_URL);
            Log.d(TAG,"Url Open");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            //connection.connect();

            String reqHead = "application/x-www-form-urlencoded";
            connection.setRequestMethod("POST");
            connection.setRequestProperty("connection","Keep-Alive"+reqHead);
            //Header header = new Header();

            MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            File file= new File(selectedFilePath);
            //file.toString(Bitmap.CompressFormat.JPEG,100,baos);
            FileBody fileBody= new FileBody(file);
            byte[] data = baos.toByteArray();
            bab = new ByteArrayBody(data, "image");


            entity.addPart("image",fileBody);
            entity.addPart("Some other String to send",new StringBody("something"));

            connection.addRequestProperty("content-length",entity.getContentLength()+"");
            connection.addRequestProperty(entity.getContentType().getName(),entity.getContentType().getValue());

            OutputStream os = connection.getOutputStream();
            entity.writeTo(connection.getOutputStream());
            os.close();
            connection.connect();

            if(connection.getResponseCode()==HttpURLConnection.HTTP_OK){
                return readStream(connection.getInputStream());
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private String readStream(InputStream inputStream) {

        BufferedReader reader;
        StringBuilder builder = new StringBuilder();

        reader = new BufferedReader(new InputStreamReader(inputStream));
        String line;
        try {
            while ((line = reader.readLine())!=null){
                builder.append(line);
            }
            response = builder.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return response;
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        if (response.equals("success")) {
            dialog.dismiss();
            Toast.makeText(getApplicationContext(), "Files Uploaded..", Toast.LENGTH_SHORT).show();
        } else
            Toast.makeText(getApplicationContext(), "Server Failed...", Toast.LENGTH_SHORT).show();
    }
}

我的网址是否有人认为URL调用是正确的?

http://somurl.com/live?header={"cameraId":"A_IVIS5045C1","encoderType":0} 

1 个答案:

答案 0 :(得分:0)

如果您正在使用MultipartEntity,那么我会建议您使用我上传的文件库(包含数据或不包含数据)。

以下是Git Url

在模块的build.gradle中添加此依赖项:

dependencies {
    compile 'com.scantity.ScHttpLibrary:ScHttpLibrary:1.0.0'
}

将您的文件添加到Hashmap中:

    HashMap<String, File> fileParameters = new HashMap<>();
    fileParameters.put("fileKey", new File(filePath));

执行开始执行

new HttpRequestResponse(MainActivity.this)
            .setOnResultListener(new HttpRequestResponse.ResultListener() {
                @Override
                public void onPostExecute(JSONObject json, String requestCode) {
                    Log.d(TAG, "json=="+json.toString());
                }
            })
            .setUrl("http://requestb.in/11xjkya1")
            .setHeaderParameters(headerParameters) // Optional
            .setStringParameters(stringParameters)
            .setFileParameters(fileParameters)
            .setMethod(HttpRequestResponse.Method.POST)
            .isDialogShown(true, "Loading...")
            .setSocketTimeOut(30)
            .executeMethod();

注意:这是一个异步任务。