How to upload File to server from android?

不羁岁月 提交于 2020-01-07 00:07:38

问题


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.

......
......
//here is the connection part
URL url = new URL(mUrl);
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false); // Don't use a Cached Copy
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("ENCTYPE", "multipart/form-data");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
connection.setRequestProperty("bill", filePath);
connection.connect();
.....
.....

private int sendFileToServer(String filePath, HttpURLConnection conn, DataOutputStream dataOutputStream, String data) throws IOException {
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1024 * 1024;

    FileInputStream fis = new FileInputStream(filePath);


    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()));
    writer.write(data);
    writer.flush();

    dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
    dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"bill\";filename=\""
            + filePath + "\"" + lineEnd);
    dataOutputStream.writeBytes(lineEnd);

    // create a buffer of maximum size
    bytesAvailable = fis.available();

    bufferSize = Math.min(bytesAvailable, maxBufferSize);
    buffer = new byte[bufferSize];

    // read file and write it into form...
    bytesRead = fis.read(buffer, 0, bufferSize);

    while (bytesRead > 0) {
        dataOutputStream.write(buffer, 0, bufferSize);
        bytesAvailable = fis.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        bytesRead = fis.read(buffer, 0,
                bufferSize);

    }
    dataOutputStream.writeBytes(lineEnd);
    dataOutputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
    Log.e(TAG, "setFileToServer: res code " + conn.getResponseCode() + " " + conn.getResponseMessage());
    return conn.getResponseCode();
}

I want to know, is there is a way to upload the file along with set of string(user data) to server or we need to separate the file uploading and string(user data).


回答1:


No, you can send together the files and values, try this and give the appropriate key value pair according to your server side code.
Note: you will need some libraries from apache.

 public static void executeMultipartPost(String url, String imgPath, String field1, String field2){
  try {
    HttpClient client = new DefaultHttpClient();
    HttpPost poster = new HttpPost(url);

    File image = new File(imgPath);  //get the actual file from the device
    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);          
    entity.addPart("field1", new StringBody(field1));
    entity.addPart("field2", new StringBody(field2));
    entity.addPart("image", new FileBody(image));
    poster.setEntity(entity );

    client.execute(poster, new ResponseHandler<Object>() {
      public Object handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
        HttpEntity respEntity = response.getEntity();
    String responseString = EntityUtils.toString(respEntity);
        // do something with the response string
    return null;
      }
    });
  } catch (Exception e){
    //do something with the error
  }
}


来源:https://stackoverflow.com/questions/37456918/how-to-upload-file-to-server-from-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!