【问题标题】:How to Upload audio from sd-card to server in android如何将音频从 sd 卡上传到 android 中的服务器
【发布时间】:2014-01-23 18:23:00
【问题描述】:

我正在尝试将音频文件从 SD 卡的特定文件夹上传到服务器。但是当我尝试这样做时,我遇到了以下错误。

error: /mnt/sdcard/AudioRecorder: open failed: EISDIR (Is a directory)

我的完整日志如下。

01-23 12:44:18.920: E/Debug(6164): error: /mnt/sdcard/AudioRecorder: open failed: EISDIR (Is a directory)
01-23 12:44:18.920: E/Debug(6164): java.io.FileNotFoundException: /mnt/sdcard/AudioRecorder: open failed: EISDIR (Is a directory)
01-23 12:44:18.920: E/Debug(6164):  at libcore.io.IoBridge.open(IoBridge.java:448)
01-23 12:44:18.920: E/Debug(6164):  at java.io.FileInputStream.<init>(FileInputStream.java:78)
01-23 12:44:18.920: E/Debug(6164):  at iqualtech.skirr.Record_AudioPG.doAudioFileUpload(Record_AudioPG.java:295)
01-23 12:44:18.920: E/Debug(6164):  at iqualtech.skirr.Record_AudioPG.stopRecording(Record_AudioPG.java:271)
01-23 12:44:18.920: E/Debug(6164):  at iqualtech.skirr.Record_AudioPG.access$0(Record_AudioPG.java:265)
01-23 12:44:18.920: E/Debug(6164):  at iqualtech.skirr.Record_AudioPG$4.onClick(Record_AudioPG.java:124)
01-23 12:44:18.920: E/Debug(6164):  at android.view.View.performClick(View.java:3517)
01-23 12:44:18.920: E/Debug(6164):  at android.view.View$PerformClick.run(View.java:14155)
01-23 12:44:18.920: E/Debug(6164):  at android.os.Handler.handleCallback(Handler.java:605)
01-23 12:44:18.920: E/Debug(6164):  at android.os.Handler.dispatchMessage(Handler.java:92)
01-23 12:44:18.920: E/Debug(6164):  at android.os.Looper.loop(Looper.java:154)
01-23 12:44:18.920: E/Debug(6164):  at android.app.ActivityThread.main(ActivityThread.java:4624)
01-23 12:44:18.920: E/Debug(6164):  at java.lang.reflect.Method.invokeNative(Native Method)
01-23 12:44:18.920: E/Debug(6164):  at java.lang.reflect.Method.invoke(Method.java:511)
01-23 12:44:18.920: E/Debug(6164):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:809)
01-23 12:44:18.920: E/Debug(6164):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:576)
01-23 12:44:18.920: E/Debug(6164):  at dalvik.system.NativeStart.main(Native Method)
01-23 12:44:18.920: E/Debug(6164): Caused by: libcore.io.ErrnoException: open failed: EISDIR (Is a directory)
01-23 12:44:18.920: E/Debug(6164):  at libcore.io.IoBridge.open(IoBridge.java:437)
01-23 12:44:18.920: E/Debug(6164):  ... 16 more

下面还有一个 logcat 是

01-23 12:44:18.926: E/AndroidRuntime(6164): FATAL EXCEPTION: main
01-23 12:44:18.926: E/AndroidRuntime(6164): java.lang.NullPointerException
01-23 12:44:18.926: E/AndroidRuntime(6164):     at iqualtech.skirr.Record_AudioPG.doAudioFileUpload(Record_AudioPG.java:344)
01-23 12:44:18.926: E/AndroidRuntime(6164):     at iqualtech.skirr.Record_AudioPG.stopRecording(Record_AudioPG.java:271)
01-23 12:44:18.926: E/AndroidRuntime(6164):     at iqualtech.skirr.Record_AudioPG.access$0(Record_AudioPG.java:265)
01-23 12:44:18.926: E/AndroidRuntime(6164):     at iqualtech.skirr.Record_AudioPG$4.onClick(Record_AudioPG.java:124)
01-23 12:44:18.926: E/AndroidRuntime(6164):     at android.view.View.performClick(View.java:3517)
01-23 12:44:18.926: E/AndroidRuntime(6164):     at android.view.View$PerformClick.run(View.java:14155)
01-23 12:44:18.926: E/AndroidRuntime(6164):     at android.os.Handler.handleCallback(Handler.java:605)
01-23 12:44:18.926: E/AndroidRuntime(6164):     at android.os.Handler.dispatchMessage(Handler.java:92)
01-23 12:44:18.926: E/AndroidRuntime(6164):     at android.os.Looper.loop(Looper.java:154)
01-23 12:44:18.926: E/AndroidRuntime(6164):     at android.app.ActivityThread.main(ActivityThread.java:4624)
01-23 12:44:18.926: E/AndroidRuntime(6164):     at java.lang.reflect.Method.invokeNative(Native Method)
01-23 12:44:18.926: E/AndroidRuntime(6164):     at java.lang.reflect.Method.invoke(Method.java:511)
01-23 12:44:18.926: E/AndroidRuntime(6164):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:809)
01-23 12:44:18.926: E/AndroidRuntime(6164):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:576)
01-23 12:44:18.926: E/AndroidRuntime(6164):     at dalvik.system.NativeStart.main(Native Method)

我的代码

private void doAudioFileUpload() {
        HttpURLConnection conn = null;
        DataOutputStream dos = null;
        DataInputStream inStream = null;
        String existingFileName = Environment.getExternalStorageDirectory()
                .getPath() + "/AudioRecorder/";

        System.out.println("Inside of doupload nd path is === "
                + existingFileName);

        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024 * 1024 * 1024;
        String urlString = "http://link to server/folder-name/upload_audio.php";
        try {
            // ------------------ CLIENT REQUEST
            FileInputStream fileInputStream = new FileInputStream(new File(
                    existingFileName));
            // open a URL connection to the Servlet
            URL url = new URL(urlString);
            // Open a HTTP connection to the URL
            conn = (HttpURLConnection) url.openConnection();
            // Allow Inputs
            conn.setDoInput(true);
            // Allow Outputs
            conn.setDoOutput(true);
            // Don't use a cached copy.
            conn.setUseCaches(false);
            // Use a post method.
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            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=\""
                    + existingFileName + "\"" + lineEnd);
            dos.writeBytes(lineEnd);
            // create a buffer of maximum size
            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            buffer = new byte[bufferSize];
            // read file and write it into form...
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
            while (bytesRead > 0) {
                dos.write(buffer, 0, bufferSize);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);
            }
            // send multipart form data necesssary after file data...
            dos.writeBytes(lineEnd);
            dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
            // close streams
            Log.e("Debug", "File is written");
            fileInputStream.close();
            dos.flush();
            dos.close();
        } catch (MalformedURLException ex) {
            Log.e("Debug", "error: " + ex.getMessage(), ex);
        } catch (IOException ioe) {
            Log.e("Debug", "error: " + ioe.getMessage(), ioe);
        }
        // ------------------ read the SERVER RESPONSE
        try {
            inStream = new DataInputStream(conn.getInputStream());
            String str;

            while ((str = inStream.readLine()) != null) {
                Log.e("Debug", "Server Response " + str);
            }
            inStream.close();

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

【问题讨论】:

  • 找不到文件路径所以返回空值!
  • stackoverflow.com/questions/9953483/… 我认为这可能会对你有所帮助
  • @mrfarts,该代码正在使用 phonegap 我没有使用过。不过谢谢你的回复。
  • "/AudioRecorder/" 是一个目录,你用它作为文件名,我想你需要把你的文件名放在那里,就像 "/AudioRecorder/audio.mp3" 等等
  • 但我想上传文件夹 AudioRecorder 的所有文件。假设这个文件夹包含超过 20 个文件。

标签: java android file file-upload fileoutputstream


【解决方案1】:

日志信息很清楚,您正在尝试上传目录,而不是文件:

String existingFileName = Environment.getExternalStorageDirectory()
                .getPath() + "/AudioRecorder/"

/AudioRecorder/ 不是音频文件。您或许应该在末尾附加音频文件名。

如果您必须上传目录中的所有文件,请考虑在 (Intent) 服务中执行此操作。

  1. 将文件名作为参数添加到您的方法中:
  2. 在您的活动中,循环进入文件列表,并针对每个文件:

    for(String filename : filesList ){
    
                    Intent intent = new Intent(this, UploadIntentService.class);
                    Bundle params = new Bundle();
                    params.putString(UploadIntentService.KEY_FILE_NAME, filename);
                    activity.startService(intent);
    }
    
  3. 服务:

    public class UploadIntentService extends IntentService {
    
    public static final String KEY_FILE_NAME= "filename";
    public UploadIntentService() {
        super("UploadIntentService");
                }
    
    @Override
    protected void onHandleIntent(Intent intent) { 
    String filename = intent.getBundle().getStringExtra(UploadIntentService.KEY_FILE_NAME);      
    
    doAudioFileUpload(filename);
           }
    
       private void doAudioFileUpload(String filename) {
        HttpURLConnection conn = null;
        DataOutputStream dos = null;
        DataInputStream inStream = null;
        String existingFileName = Environment.getExternalStorageDirectory()
                .getPath() + "/AudioRecorder/"+filename;
    
        System.out.println("Inside of doupload nd path is === "
                + existingFileName);
    
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024 * 1024 * 1024;
        String urlString = "http://link to server/folder-name/upload_audio.php";
        try {
            // ------------------ CLIENT REQUEST
            FileInputStream fileInputStream = new FileInputStream(new File(
                    existingFileName));
            // open a URL connection to the Servlet
            URL url = new URL(urlString);
            // Open a HTTP connection to the URL
            conn = (HttpURLConnection) url.openConnection();
            // Allow Inputs
            conn.setDoInput(true);
            // Allow Outputs
            conn.setDoOutput(true);
            // Don't use a cached copy.
            conn.setUseCaches(false);
            // Use a post method.
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            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=\""
                    + existingFileName + "\"" + lineEnd);
            dos.writeBytes(lineEnd);
            // create a buffer of maximum size
            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            buffer = new byte[bufferSize];
            // read file and write it into form...
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
            while (bytesRead > 0) {
                dos.write(buffer, 0, bufferSize);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);
            }
            // send multipart form data necesssary after file data...
            dos.writeBytes(lineEnd);
            dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
            // close streams
            Log.e("Debug", "File is written");
            fileInputStream.close();
            dos.flush();
            dos.close();
        } catch (MalformedURLException ex) {
            Log.e("Debug", "error: " + ex.getMessage(), ex);
        } catch (IOException ioe) {
            Log.e("Debug", "error: " + ioe.getMessage(), ioe);
        }
        // ------------------ read the SERVER RESPONSE
        try {
            inStream = new DataInputStream(conn.getInputStream());
            String str;
    
            while ((str = inStream.readLine()) != null) {
                Log.e("Debug", "Server Response " + str);
            }
            inStream.close();
    
        } catch (IOException ioex) {
            Log.e("Debug", "error: " + ioex.getMessage(), ioex);
        }
    }   
    

    希望对你有帮助

PS:未经测试的代码。

【讨论】:

  • 是的,但我想上传 AudioRecorder 文件夹中存在的所有文件,所以我该如何实现。
  • 我不知道该怎么做。如果有,请发布任何代码 sn-p 或示例。这对您有很大的帮助。
  • 好的,使用 IntentService 类依次上传文件。
猜你喜欢
  • 1970-01-01
  • 2014-08-14
  • 1970-01-01
  • 2011-09-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多