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

我想将音频文件上传到服务器。

我可以通过上面的代码将音频文件上传到服务器,但文件不工作(不在系统中播放)。如果你有任何想法,请帮助我。

4

2 回答 2

2

您应该既不使用FileReader也不使用StringBuilder此处,因为它将数据视为字符(根据默认系统字符集编码)。真的,你根本不应该使用 a Reader。二进制数据应通过处理InputStream,例如

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();
于 2012-08-27T18:10:55.287 回答
0

你检查服务器上的校验和了吗?它到达时未经修改吗?

如果没有,请尝试其他方法发布文件。这对我帮助很大:

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

这取自:

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

检查依赖项和使用情况的链接。

于 2012-08-27T18:08:04.200 回答