0

HI,

i use the following part of code to upload file into server, along with this file i need to send some parameter regarding this file, i don`t know how to send the parameter along with file , but i can able to upload the file.

               FileInputStream fileInputStream = new FileInputStream(sourceFile);
       URL url = new URL(upLoadServerUri);
       conn = (HttpURLConnection) url.openConnection(); 

       conn.setDoInput(true); // Allow Inputs
       conn.setDoOutput(true); // Allow Outputs
       conn.setUseCaches(false); // Don't use a Cached Copy
       conn.setRequestMethod("POST");

       conn.setRequestProperty("Connection", "Keep-Alive");
       conn.setRequestProperty("ENCTYPE", "multipart/form-data");

       conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);


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

       dos.writeBytes(twoHyphens + boundary + lineEnd);
       dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\""+ fileName + "\"" + lineEnd);
       dos.writeBytes(lineEnd);

       bytesAvailable = fileInputStream.available(); 



       bufferSize=(int)sourceFile.length();


       buffer = new byte[1024];
       int len;
       int state=0;
       while((len=fileInputStream.read(buffer))>0){
           state=state+len;
           dos.write(buffer);
           publishProgress(state);
       }

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

       // Responses from the server (code and message)
       serverResponseCode = conn.getResponseCode();
       String serverResponseMessage = conn.getResponseMessage();


       // close streams
       Log.i("Upload file to server", fileName + " File is written");
       fileInputStream.close();
       dos.flush();
       dos.close();
      } catch (MalformedURLException ex) {
       ex.printStackTrace();
       Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
      } catch (Exception e) {
       e.printStackTrace();
      }
    //this block will give the response of upload link
      try {
       BufferedReader rd = new BufferedReader(new InputStreamReader(conn
         .getInputStream()));

       while ((line = rd.readLine()) != null) {
        Log.i("Huzza", "RES Message: " + line);


       }
       rd.close();
      } catch (IOException ioex) {
       Log.e("Huzza", "error: " + ioex.getMessage(), ioex);

      }

if any one knows the problem help me out.

Karthi
  • 13,624
  • 10
  • 53
  • 76

1 Answers1

0

Use http client with multipart entities. you will need additional libs for that.

here is a nice post about how to do that:

MultipartEntity

Community
  • 1
  • 1
DArkO
  • 15,880
  • 12
  • 60
  • 88