KSP
KSP

Reputation: 83

How to send an audio file to server in android?

public static String fileUploadFromPath(String url, String path) throws Throwable {

        System.out.println("IN fileUploadFromPath ");
        String responseData = "";
        String NL = System.getProperty("line.separator");

        try {

            System.out.println("url ************ " + url);
            File file = new File(path);
            System.out.println("file ************ " + file.getAbsolutePath()
                    + " : " + file.exists());
            StringBuilder text = new StringBuilder();

            if (file.exists()) {
                BufferedReader br = new BufferedReader(new FileReader(file));
                String line;

                while ((line = br.readLine()) != null) {
                    text.append(line);
                    text.append(NL);
                }
                HttpClient httpClient = new DefaultHttpClient();
                HttpPost postRequest = new HttpPost(url);
                // System.out.println("postRequest ************ " +
                // postRequest);
                MultipartEntity multipartContent = new MultipartEntity();
                ByteArrayBody key = new ByteArrayBody(text.toString()
                        .getBytes(), AgricultureUtils.getInstance()
                        .getTimeStamp() + ".3gp");
                multipartContent.addPart(AgricultureUtils.getInstance()
                        .getTimeStamp() + ".3gp", key);
                postRequest.setEntity(multipartContent);
                HttpResponse response = httpClient.execute(postRequest);
                BufferedReader in = new BufferedReader(new InputStreamReader(
                        response.getEntity().getContent()));
                StringBuffer sb = new StringBuffer("");
                String content = "";
                while ((content = in.readLine()) != null) {
                    sb.append(content + NL);
                }
                in.close();

                /*
                 * File myDir = new File(Constants.dirctory); if
                 * (!myDir.exists()) { myDir.mkdirs(); } File myFile = new
                 * File(myDir, fileName); FileOutputStream mFileOutStream = new
                 * FileOutputStream(myFile);
                 * mFileOutStream.write(sb.toString().getBytes());
                 * mFileOutStream.flush(); mFileOutStream.close();
                 */

                System.out.println("response " + sb);
            }

        } catch (Throwable e) {
            System.out.println("Exception In Webservice ----- " + e);
            throw e;
        }
        return responseData;
    }

I want to upload an audio file into server.

I am able upload audio file to server through above code but the file is not working(not playing in system). If u have any idea please help me.

Upvotes: 1

Views: 5311

Answers (2)

slavemaster
slavemaster

Reputation: 204

You should be using neither FileReader nor StringBuilder here as it treats the data as characters (encoded according to the default system character set). Really, you should not be using a Reader at all. Binary data should be handled via InputStream, e.g.

final ByteArrayOutputStream out = new ByteArrayOutputStream();
try (final InputStream in = new FileInputStream(file)) {
  final byte[] buf = new byte[2048];
  int n;
  while ((n = in.read(buf)) >= 0) {
    out.write(buf, 0, n);
  }
}
final byte[] data = out.toByteArray();

Upvotes: 2

Jorge Cevallos
Jorge Cevallos

Reputation: 3678

Did you check checksum on server? Is it arriving unmodified?

If not, try other method to post files. This one helped me a lot:

       /**
        * Post request (upload files)
        * @param sUrl
        * @param params Form data
        * @param files
        * @return
        */
        public static HttpData post(String sUrl, Hashtable<String, String> params, ArrayList<File> files) {
                HttpData ret = new HttpData();
                try {
                        String boundary = "*****************************************";
                        String newLine = "rn";
                        int bytesAvailable;
                        int bufferSize;
                        int maxBufferSize = 4096;
                        int bytesRead;

                        URL url = new URL(sUrl);
                        HttpURLConnection con = (HttpURLConnection) url.openConnection();
                        con.setDoInput(true);
                        con.setDoOutput(true);
                        con.setUseCaches(false);
                        con.setRequestMethod("POST");
                        con.setRequestProperty("Connection", "Keep-Alive");
                        con.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
                        DataOutputStream dos = new DataOutputStream(con.getOutputStream());

                        //dos.writeChars(params);

                        //upload files
                        for (int i=0; i<files.size(); i++) {
                                Log.i("HREQ", i+"");
                                FileInputStream fis = new FileInputStream(files.get(i));
                                dos.writeBytes("--" + boundary + newLine);
                                dos.writeBytes("Content-Disposition: form-data; "
                                + "name="file_"+i+"";filename=""
                                + files.get(i).getPath() +""" + newLine + newLine);
                                bytesAvailable = fis.available();
                                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                                byte[] buffer = new byte[bufferSize];
                                bytesRead = fis.read(buffer, 0, bufferSize);
                                while (bytesRead > 0) {
                                        dos.write(buffer, 0, bufferSize);
                                        bytesAvailable = fis.available();
                                        bufferSize = Math.min(bytesAvailable, maxBufferSize);
                                        bytesRead = fis.read(buffer, 0, bufferSize);
                                }
                                dos.writeBytes(newLine);
                                dos.writeBytes("--" + boundary + "--" + newLine);
                                fis.close();
                        }
                        // Now write the data

                        Enumeration keys = params.keys();
                        String key, val;
                        while (keys.hasMoreElements()) {
                                key = keys.nextElement().toString();
                                val = params.get(key);
                                dos.writeBytes("--" + boundary + newLine);
                                dos.writeBytes("Content-Disposition: form-data;name=""
                                + key+""" + newLine + newLine + val);
                                dos.writeBytes(newLine);
                                dos.writeBytes("--" + boundary + "--" + newLine);

                        }
                        dos.flush();

                        BufferedReader rd = new BufferedReader(
                        new InputStreamReader(con.getInputStream()));
                        String line;
                        while ((line = rd.readLine()) != null) {
                                ret.content += line + "rn";
                        }
                        //get headers
                        Map<String, List<String>> headers = con.getHeaderFields();
                        Set<Entry<String, List<String>>> hKeys = headers.entrySet();
                        for (Iterator<Entry<String, List<String>>> i = hKeys.iterator(); i.hasNext();) {
                                Entry<String, List<String>> m = i.next();

                                Log.w("HEADER_KEY", m.getKey() + "");
                                ret.headers.put(m.getKey(), m.getValue().toString());
                                if (m.getKey().equals("set-cookie"))
                                ret.cookies.put(m.getKey(), m.getValue().toString());
                        }
                        dos.close();
                        rd.close();
                } catch (MalformedURLException me) {

                } catch (IOException ie) {

                } catch (Exception e) {
                        Log.e("HREQ", "Exception: "+e.toString());
                }
                return ret;
        }

This is taken from:

http://moazzam-khan.com/blog/?p=490

Check link for dependencies and usage.

Upvotes: 0

Related Questions