【问题标题】:Unable to upload a file to server in android?无法将文件上传到android中的服务器?
【发布时间】:2016-06-07 12:11:05
【问题描述】:

我在将文件上传到服务器时遇到问题。这里我正在尝试创建注册表单。

我需要上传从用户那里获取的所有值,以及我需要上传 PDF 格式的简历。

这是我的代码。请仔细查看。

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

问题是当我将数据发送到 url("http://www.example.com") 时,上面的代码有效,但它不适用于 url("https://www.example.com")。

谁能告诉我的代码有什么问题。

请帮帮我。

编辑:我在服务器端检查了来自 android 的请求,我在请求中发现了空数据,它以默认消息响应(在服务器中设置的响应)。

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

刚才我检查了一下,这个相同的 URL 在网站上可以正常工作。

如果我错了,请以正确的方式指导我

提前致谢。

【问题讨论】:

  • 我猜,也许你的https url 没有用 ssl 证书签名,服务器可能用SSLHandshakeException 响应。如果您遇到任何异常,请检查您的堆栈跟踪
  • 但我将数据(无文件)发送到具有相同域的服务器并且它可以工作。您说 SSL 未登录服务器,您可以通过参考链接指导我。
  • @sripadRaj 我已经更新了我的问题,请参阅我的编辑
  • 我不确定,不能说你的代码是错误的还是服务器端的问题。用 try catch 块包围你的代码,检查你是否遇到任何异常。还要检查来自服务器的响应代码。

标签: java android file-upload https apache-httpclient-4.x


【解决方案1】:

试试这个代码,希望对你有帮助。

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

【讨论】:

  • 会试试这个并告诉你
  • 它不起作用,我已经更新了我的问题,请查看我的编辑。
【解决方案2】:

我使用这段代码发布文件。应该在后台线程中使用,函数将返回服务器响应。

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

【讨论】:

  • 我也试过这个,它类似于@MustanserIqbal 的答案。我已经更新了我的问题,请查看我的编辑
【解决方案3】:

使用 Retrofit 上传文件。 它更快更容易

创建接口

公共接口 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);

}

调用这个方法

公共无效同步照片() {

    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: ");
        }
    });


}

将依赖项添加到 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'

检查此链接 https://futurestud.io/tutorials/retrofit-2-how-to-upload-files-to-server

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-04
    • 2013-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多