简体   繁体   中英

Unable to upload a file to server in android?

I have a problem with uploading file to the server. Here i'm trying to create the registration form.

I need to upload all values that taken from user, along with that i need to upload the resume resume is in PDF format.

Here is my code. Please look into it.

      public String serverResponse(String mFilePath){
        HttpClient client = new DefaultHttpClient();
        HttpPost poster = new HttpPost(mUrl);

        File resume = new File(mFilePath);  //Actual file from the device
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        entity.addPart("name", new StringBody("name"));
        entity.addPart("phone", new StringBody("1234567890"));
        entity.addPart("attachment", new FileBody(resume));
        poster.setEntity(entity);

        return client.execute(poster, new ResponseHandler<String>() {
            public String handleResponse(HttpResponse response) throws IOException {
                HttpEntity respEntity = response.getEntity();

                return EntityUtils.toString(respEntity);
            }
        });
      }

The problem is above code works when i send the data to url( " http://www.example.com " ), and it doesn't works on the url( " https://www.example.com " ).

can anyone tell what's wrong on my code.

Please help me on this.

Edit : I checked the request from android in server side, there i found empty data in request and it response back with default message(response that set in server).

so my request hits the server with empty values. Is problem in my code (or) server side ?

just now i checked, that this same URL works fine in website.

Please direct me in correct way if i was wrong

Thanks in Advance.

try this code i hope this will help you.

public String uploadFile(String filePath, String name, String phone, String url) throws Exception {

        String crlf = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";

        HttpURLConnection httpUrlConnection = null;
        OutputStream outputStream = null;
        InputStream inputStream = null;
        InputStreamReader in = null;
        try {
            URL urlObj = new URL(url);
            httpUrlConnection = (HttpURLConnection) urlObj.openConnection();
            httpUrlConnection.setReadTimeout(10 * 1000);
            httpUrlConnection.setConnectTimeout(10 * 1000);
            httpUrlConnection.setDoInput(true);
            File file = new File(filePath);
            if (file != null) {
                httpUrlConnection.setUseCaches(false);
                httpUrlConnection.setRequestMethod("POST");

                httpUrlConnection.setRequestProperty("Connection", "Keep-Alive");
                httpUrlConnection.setRequestProperty("Cache-Control", "no-cache");
                httpUrlConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

                outputStream = httpUrlConnection.getOutputStream();

                outputStream.write((crlf + twoHyphens + boundary + crlf).getBytes());
                outputStream.write(("Content-Disposition: form-data; name=\"name\"" + crlf + crlf + name).getBytes());
                outputStream.write((crlf + twoHyphens + boundary + crlf).getBytes());
                outputStream.write(("Content-Disposition: form-data; name=\"phone\"" + crlf + crlf + phone).getBytes());
                outputStream.write((crlf + twoHyphens + boundary + crlf).getBytes());

                Log.e("Response :", "Response Code : " + file.getName());

                outputStream.write(("Content-Disposition: form-data; name=\"file\"; filename=\""
                        + file.getName()
                        + "\""
                        + crlf
                        + "Content-Type: image/jpeg" + crlf).getBytes());

                outputStream.write(crlf.getBytes());

                FileInputStream fis = new FileInputStream(file);

                byte[] buffer = new byte[1024];

                int length;

                while ((length = fis.read(buffer)) > 0) {
                    outputStream.write(buffer, 0, length);
                }

                outputStream.write(crlf.getBytes());
                outputStream.write((twoHyphens + boundary + twoHyphens + crlf).getBytes());

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

            httpUrlConnection.connect();

            Log.e("Response :", "Response Code : " + httpUrlConnection.getResponseCode());

            if (httpUrlConnection.getResponseCode() == -1) {

                onImageUploadCompleted.onImageUploadCompleted("error -1");
                Log.e("Connection error", "Connection error: url " + url);
                String json = "{\"error\": {\"code\": 991, \"message\": \"Connection error: `991`\"}}";
            }

            if (httpUrlConnection.getResponseCode() == 204) {
                return "Upload failed";
            }
            if (httpUrlConnection.getResponseCode() == 200) {
                inputStream = httpUrlConnection.getInputStream();
            }
            else
                inputStream = httpUrlConnection.getErrorStream();

            in = new InputStreamReader(inputStream);

            StringBuilder sb = new StringBuilder();

            int read;

            char[] buff = new char[1024];

            while ((read = in.read(buff)) != -1) {
                sb.append(buff, 0, read);
            }

            File f = new File(filePath);
            f.delete();
            Log.e("Response ", "Response text : " + sb.toString());

            if (httpUrlConnection.getResponseCode() != 200) {
                //ParseJson.parseException(sb.toString());
                Log.e("Failed", "Failed safe : " + sb.toString());
                return sb.toString();
            }

            return sb.toString();
        } catch (Exception e) {
            if (outputStream != null) {
                outputStream.close();
            }

            if (in != null) {
                in.close();
            }

            if (inputStream != null) {
                inputStream.close();
            }
            e.printStackTrace();
        } finally {
            if (httpUrlConnection != null) {
                httpUrlConnection.disconnect();
            }

        }
        return null;
    }

I use this code to post a file.Should be used in background thread, and function will return the server response.

    public String postFile(String mFileName,String apiUrl,String fileType,HashMap<String,String> params) throws Exception{

    String output = "null";
    HttpURLConnection connection = null;
    DataOutputStream outputStream = null;
    InputStream inputStream = null;

    String twoHyphens = "--";
    String boundary = "*****" + Long.toString(System.currentTimeMillis())
            + "*****";
    String lineEnd = "\r\n";

    String result = "";

    int bytesRead, bytesAvailable, bufferSize, bytesTransffered, bytesTotals;
    byte[] buffer;
    int maxBufferSize = 10;

    String[] q = mFileName.split("/");
    int idx = q.length - 1;


    File file = new File(mFileName);
    FileInputStream fileInputStream = new FileInputStream(file);
    URL url = new URL(apiUrl);
    connection = (HttpURLConnection) url.openConnection();

    connection.setDoInput(true);
    connection.setDoOutput(true);
    connection.setUseCaches(false);

    connection.setRequestMethod("POST");
    connection.setRequestProperty("Connection", "Keep-Alive");
    connection.setRequestProperty("User-Agent",
            "Android Multipart HTTP Client 1.0");
    connection.setRequestProperty("Content-Type",
            "multipart/form-data; boundary=" + boundary);

    outputStream = new DataOutputStream(connection.getOutputStream());
    outputStream.writeBytes(twoHyphens + boundary + lineEnd);
    Log.d(TAG, "msg is " + q[idx]);
    outputStream.writeBytes("Content-Disposition: form-data; name=\""
            + "file" + "\"; filename=\"" + q[idx] + "\"" + lineEnd);

    outputStream.writeBytes("Content-Type: " + fileType + lineEnd);

    outputStream.writeBytes("Content-Transfer-Encoding: binary"
            + lineEnd);

    outputStream.writeBytes(lineEnd);

    bytesAvailable = fileInputStream.available();
    long bytesTotal = file.length();
    bufferSize = Math.min(bytesAvailable, maxBufferSize);
    buffer = new byte[bufferSize];

    bytesTransffered = 0;
    bytesRead = fileInputStream.read(buffer, 0, bufferSize);
    bytesTransffered = bytesRead;
    while (bytesRead > 0) {
        outputStream.write(buffer, 0, bufferSize);
        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        bytesTransffered += bytesRead;
        if (mProgressUpdateListener != null) {
            publishProgress((100 * bytesTransffered)
                    / Integer.parseInt(bytesTotal + ""));

        } else {
            Log.d(TAG, "Progress Listener is Null");
        }
    }

    outputStream.writeBytes(lineEnd);

    Iterator it = params.entrySet().iterator();

    while (it.hasNext()) {
        Map.Entry pair = (Map.Entry)it.next();
        String key= (String) pair.getKey();
        String value = (String) pair.getValue();
        outputStream.writeBytes(twoHyphens + boundary + lineEnd);
        outputStream.writeBytes("Content-Disposition: form-data; name=\"" + key + "\"" + lineEnd);
        outputStream.writeBytes("Content-Type: text/plain" + lineEnd);
        outputStream.writeBytes(lineEnd);
        outputStream.writeBytes(value);
        outputStream.writeBytes(lineEnd);

        outputStream.writeBytes(twoHyphens + boundary + twoHyphens
                + lineEnd);

    }

    Log.d(TAG,"Response code "+connection.getResponseCode());
    if (connection.getResponseCode() == 200) {

        InputStream in = connection.getInputStream();
        BufferedReader rd = new BufferedReader(
                new InputStreamReader(in));
        output = "";
        String line;
        while ((line = rd.readLine()) != null) {
            output += line;
        }


    }

    return output;
}

Use Retrofit to uplaod a file. It is faster and easy

Create an interface

public interface ApiClient {

@Multipart
@POST(NetworkUtils.UPLOAD_PHOTO_URL)
Call<PhotoResponseModel> uploadPhoto(
        @Header("id") String id,
        @Header("imageId") String imageId,
        /*@Part("description") RequestBody description,*/
        @Part MultipartBody.Part photo);

}

call this method

public void syncPhoto() {

    Retrofit.Builder builder = new Retrofit.Builder()
            .baseUrl(NetworkUtils.SERVER_PATH)
            .addConverterFactory(GsonConverterFactory.create());

    Retrofit retrofit = builder.build();
    ApiClient apiClient = retrofit.create`(ApiClient.class);

    RequestBody filePart = RequestBody.create(/*MediaType.parse(context.getContentResolver().getType(Uri.parse(photoDetails.getImageUrl())))*/
            MediaType.parse("image/*"),
            file);

    MultipartBody.Part fileMultiPart = MultipartBody.Part.createFormData("photo", file.getName(), filePart);

    Call<PhotoResponseModel> call = apiClient.uploadPhoto(id, imageId, fileMultiPart);

    call.enqueue(new Callback<PhotoResponseModel>() {
        @Override
        public void onResponse(Call<PhotoResponseModel> call, Response<PhotoResponseModel> response) {

                }
            }
        }

        @Override
        public void onFailure(Call<PhotoResponseModel> call, Throwable t) {
            Log.d("Error", "onFailure: ");
        }
    });


}

Add dependencies to gradle

compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
compile 'com.squareup.okhttp3:logging-interceptor:3.3.1'

check this link https://futurestud.io/tutorials/retrofit-2-how-to-upload-files-to-server

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