2011-09-08 38 views
0

如何从服务器下载音频文件的url并将其保存到SD卡。如何从服务器下载音频文件的url

我使用下面的代码:

public void uploadPithyFromServer(String imageURL, String fileName) { 

    try { 
     URL url = new URL(GlobalConfig.AppUrl + imageURL); 
     File file = new File(fileName); 

     Log.d("ImageManager", "download begining"); 
     Log.d("ImageManager", "download url:" + url); 
     Log.d("ImageManager", "downloaded file name:" + fileName); 
     /* Open a connection to that URL. */ 
     URLConnection con = url.openConnection(); 

     InputStream is = con.getInputStream(); 
     BufferedInputStream bis = new BufferedInputStream(is, 1024 * 50); 
     FileOutputStream fos = new FileOutputStream("/sdcard/" + file); 
     byte[] buffer = new byte[1024 * 50]; 

     int current = 0; 
     while ((current = bis.read(buffer)) != -1) { 
      fos.write(buffer, 0, current); 
     } 

     fos.flush(); 
     fos.close(); 
     bis.close(); 

    } catch (IOException e) { 
     Log.d("ImageManager", "Error: " + e); 
    } 

} 

上面的代码不下载音频文件。 如果menifest文件中使用的任何许可PLZ告诉我..(我用互联网许可) 请帮助

感谢..

+0

你怎么知道音频文件没有被下载? – slayton

回答

2

还必须添加

android.permission.WRITE_EXTERNAL_STORAGE

权限,如果你想写入数据到SD卡。

也发布您的logcat输出,如果您收到任何IOExceptions。

2

你的例子没有指定请求方法和一些mimetypes和东西。
在这里您可以找到mimetypes列表http://www.webmaster-toolkit.com/mime-types.shtml
查找与您相关的mimetypes并将其添加到代码中指定的mimetypes中。

哦,顺便说一句,下面是普通的Java代码。你将不得不将存储在SD卡上的文件替换掉。不要有一个仿真器或电话的那一刻 来测试部分也可参阅SD存储权限的文档在这里:http://developer.android.com/reference/android/Manifest.permission_group.html#STORAGE

public static void downloadFile(String hostUrl, String filename) 
    { 
    try {  
    File file = new File(filename); 
    URL server = new URL(hostUrl + file.getName()); 


    HttpURLConnection connection = (HttpURLConnection)server.openConnection(); 
    connection.setRequestMethod("GET"); 
    connection.setDoInput(true); 
    connection.setDoOutput(true); 
    connection.setUseCaches(false); 
    connection.addRequestProperty("Accept","image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/msword, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/x-shockwave-flash, */*"); 
    connection.addRequestProperty("Accept-Language", "en-us,zh-cn;q=0.5"); 
    connection.addRequestProperty("Accept-Encoding", "gzip, deflate"); 

    connection.connect(); 
    InputStream is = connection.getInputStream(); 
    OutputStream os = new FileOutputStream("c:/temp/" + file.getName()); 

    byte[] buffer = new byte[1024]; 
    int byteReaded = is.read(buffer); 
    while(byteReaded != -1) 
    { 
     os.write(buffer,0,byteReaded); 
     byteReaded = is.read(buffer); 
    } 

    os.close(); 

    } catch (IOException e) { 
    e.printStackTrace(); 
    } 

然后调用,

downloadFile("http://localhost/images/bullets/", "bullet_green.gif"); 

编辑: 坏编码器我。 将输入InputStream包装在BufferedInputStream中。无需指定buffersizes等。
默认值是好的。