用于使用多部分表单数据将图像和json请求上载到服务器的Android代码

时间:2015-09-03 19:42:52

标签: android json httpurlconnection

所以我在apache实现中使用MultiPartEntity多次提前完成此操作,但现在弃用了我需要使用HTTPUrlConnection的API。

我的服务器端脚本在php

中看起来像这样
    $userData = urldecode ( $_POST['form'] );
    $json = json_decode ( $userData );
    $username = $json->emailAddress;
    $this->load->model( 'rest_image_upload_model' );
    $result = $this->rest_image_upload_model->checkCredentialsAndReturnUserId ($username, $password);
    $userId = $result ['mfwid'];

    if($userId == 0 || empty($userId) || false == $result){
        $responseJson['success'] = false;
        $responseJson['message'] = "Username could not be fetched. Contact system admin.";
        echo json_decode($responseJson);
        return;
    }

    $firstName = '';
    $result = $this->rest_image_upload_model->fetchUsersName( $userId );
    $firstName = $result ['first_name'];

    if(empty($firstName) || false == $result){
        $responseJson['success'] = false;
        $responseJson['message'] = "First Name could not be fetched. Contact system admin.";
        echo json_decode($responseJson);
        return;
    }
    //end of json part

    // Start creating a floder for the image to be uploaded
    $foldername = $firstName . '-' . $userId;
    if (! is_dir ( 'download/upload/profile/' . $date . '/' . $foldername )){
        mkdir ( './download/upload/profile/' . $date . '/' . $foldername, 0777, TRUE );
   }
    $config ['upload_path'] = './download/upload/profile/' . $date . '/' . $foldername;
    $thumbnailRefFilePath = $config['upload_path'];
    $config ['allowed_types'] = "jpg|png|JPEG|jpeg|PNG|JPG"; // 'gif|jpg|png|tiff';
    $config ['max_size'] = '10240';
    $config ['max_width'] = '5000';
    $config ['max_height'] = '5000';
    $this->load->library ( 'upload', $config );
    $this->upload->initialize ( $config );
    if (! $this->upload->do_upload ( 'image' )) { // if uploading image failed
        $responseJson['success'] = false;
        $responseJson['message'] = "File Not Uploaded";
        //$upload_data['file_name']='nopic.png';
        echo json_encode($responseJson);
        return;
    } else { 

        // uploading image success
        $upload_data = $this->upload->data(); // save
      }

Android代码似乎上传了json部分,但我收到错误。文件没有上传到json中。下面是我的Android代码。

public StringBuilder doMultipartPost(String api,
                                         String jsonPost,
                                         String jsonPartKey,
                                         String filePath,
                                         String filePathKey) throws InstyreNetworkException{

        String boundary = UUID.randomUUID().toString();
        String twoHyphens = "--";
        //String attachmentName = "data";
        String crlf = "\r\n";
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024 * 1024;

        try {
            final String URL = NetworkUtils.BASE_URL + api;
            URI uri = new URI(URL);
            HttpURLConnection urlConnection = (HttpURLConnection) uri.toURL().openConnection();
            urlConnection.setRequestMethod("POST");
            urlConnection.setRequestProperty("Connection", "Keep-Alive");
            urlConnection.setDoInput(true);
            urlConnection.setDoOutput(true);
            urlConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

            DataOutputStream dos = new DataOutputStream(urlConnection.getOutputStream());

            // FIRST PART; A JSON object
            dos.writeBytes(twoHyphens + boundary);
            dos.writeBytes(crlf);
            dos.writeBytes("Content-Type: application/json");
            dos.writeBytes(crlf);
            dos.writeBytes("Content-Disposition: form-data; name=\""+jsonPartKey+"\"");
            dos.writeBytes(crlf);
            dos.writeBytes(crlf);
            dos.writeBytes(jsonPost);
            dos.writeBytes(crlf);

            // SECOND PART; A image..
            File file = new File(filePath);
            FileInputStream fileInputStream = new FileInputStream(file);
            dos.writeBytes(twoHyphens + boundary);
            dos.writeBytes(crlf);
            dos.writeBytes("Content-Type: jpg");
            dos.writeBytes(crlf);
            dos.writeBytes("Content-Disposition: form-data; name=\"image\"");
           // dos.writeBytes("Content-Disposition: form-data; name=\"attachment_0\";filename=\"" + file.getName() + "\"" + lineEnd);
            dos.writeBytes(crlf);
            dos.writeBytes(crlf);
            dos.writeBytes("Content-Length: " + file.length() + crlf);
            dos.writeBytes(crlf);
            dos.writeBytes(crlf);
            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            buffer = new byte[bufferSize];
            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);
            }

            dos.writeBytes(crlf);
            dos.writeBytes(twoHyphens + boundary + crlf);
            fileInputStream.close();

            // start reading response
            InputStream is = urlConnection.getInputStream();
            BufferedReader streamReader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            StringBuilder responseStrBuilder = new StringBuilder();
            String inputStr;
            while ((inputStr = streamReader.readLine()) != null)
                responseStrBuilder.append(inputStr);
            is.close();
            dos.close();
        } catch (Exception e) {
             e.printStackTrace();
        }
        return null;
    } 

1 个答案:

答案 0 :(得分:-1)

我在这里找到了零件解决方案 http://www.codejava.net/java-se/networking/upload-files-by-sending-multipart-request-programmatically

public StringBuilder doMultipartPost(String api,
                                         String jsonPost,
                                         String jsonPartKey,
                                         String filePath,
                                         String filePathKey) throws NetworkException{

    String boundary = UUID.randomUUID().toString();
    String twoHyphens = "--";
    String crlf = "\r\n";

    try {
        final String URL = NetworkUtils.BASE_URL + api;
        URI uri = new URI(URL);
        HttpURLConnection urlConnection = (HttpURLConnection) uri.toURL().openConnection();
        urlConnection.setRequestMethod("POST");
        urlConnection.setRequestProperty("Connection", "Keep-Alive");
        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(true);
        urlConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

        OutputStream outputStream =  urlConnection.getOutputStream();
        DataOutputStream dos = new DataOutputStream(outputStream);

        // FIRST PART; A JSON object
        dos.writeBytes(twoHyphens + boundary);
        dos.writeBytes(crlf);
        dos.writeBytes("Content-Type: application/json");
        dos.writeBytes(crlf);
        dos.writeBytes("Content-Disposition: form-data; name=\""+jsonPartKey+"\"");
        dos.writeBytes(crlf);
        dos.writeBytes(crlf);
        dos.writeBytes(jsonPost);
        dos.writeBytes(crlf);

        File uploadFile = new File(filePath);
        String fileName = uploadFile.getName();
        PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream, "UTF-8"),
                true);
        writer.append("--" + boundary).append(crlf);
        writer.append(
                "Content-Disposition: form-data; name=\"" + filePathKey
                        + "\"; filename=\"" + fileName + "\"")
                .append(crlf);
        writer.append(
                "Content-Type: "
                        + URLConnection.guessContentTypeFromName(fileName))
                .append(crlf);
        writer.append("Content-Transfer-Encoding: binary").append(crlf);
        writer.append(crlf);
        writer.flush();

        FileInputStream inputStream = new FileInputStream(uploadFile);
        byte[] buffer = new byte[4096];
        int bytesRead = -1;
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }
        writer.append(crlf);
        writer.append(twoHyphens + boundary + crlf);
        outputStream.flush();
        inputStream.close();

        writer.flush();

        // start reading response
        InputStream is = urlConnection.getInputStream();
        BufferedReader streamReader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        StringBuilder responseStrBuilder = new StringBuilder();
        String inputStr;
        while ((inputStr = streamReader.readLine()) != null)
            responseStrBuilder.append(inputStr);
        is.close();
        dos.close();
        return responseStrBuilder;
    } catch (Exception e) {
         e.printStackTrace();
    }
    return null;
}