0

我正在尝试将图像和歌曲等文件上传到我的 PHP 服务器,但是当我尝试上传大文件(文件大小 5MB 或更大)时,我遇到了一些错误。我能够成功上传接近 500kb 的文件。请帮助我让我知道如何上传大文件大小..

java文件的代码:

public class UploadAudioDemo extends Activity {

    private static final int SELECT_IMAGE = 1, SELECT_AUDIO = 2;
    String selectedPath = "";
    Button ImageBtn, AudioBtn;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        ImageBtn = (Button)findViewById(R.id.image_btn);
        AudioBtn = (Button)findViewById(R.id.audio_btn);
        ImageBtn.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent,"Select Image"), SELECT_IMAGE);
            }
        });
        AudioBtn.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent intent = new Intent();
                intent.setType("audio/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent,"Select Audio"), SELECT_AUDIO);
            }
        });
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (resultCode == RESULT_OK) {
            if (requestCode == SELECT_IMAGE)
            {
                System.out.println("SELECT_IMAGE");
                Uri selectedImageUri = data.getData();
                selectedPath = getPath(selectedImageUri);
                System.out.println("SELECT_IMAGE Path : " + selectedPath);
                doFileUpload();
            }
            else if(requestCode == SELECT_AUDIO)
            {
                System.out.println("SELECT_AUDIO");
                Uri selectedImageUri = data.getData();
                selectedPath = getPath(selectedImageUri);
                System.out.println("SELECT_AUDIO Path : " + selectedPath);
                doFileUpload();
            }
        }
    }

    public String getPath(Uri uri) {
        String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = managedQuery(uri, projection, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }

    private void doFileUpload(){
        HttpURLConnection conn = null;
        DataOutputStream dos = null;
        DataInputStream inStream = null;
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary =  "*****";
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1*1024*1024*1024;
        String urlString = "http://abhishekpnf.my3gb.com/test/testupload.php";
        try
        {
            FileInputStream fileInputStream = new FileInputStream(new File(selectedPath) );
            URL url = new URL(urlString);
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setUseCaches(false);
            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=\"" + selectedPath + "\"" + lineEnd);
            dos.writeBytes(lineEnd);
            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            buffer = new byte[bufferSize];
            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);
            }
            dos.writeBytes(lineEnd);
            dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
            Log.v("Debug","File is written");
            fileInputStream.close();
            dos.flush();
            dos.close();
        }
        catch(SocketException ex)
        {
          Log.v("Error : " , "Error on soapPrimitiveData() " + ex.getMessage());
            ex.printStackTrace();
        }
        catch (MalformedURLException ex)
        {
             Log.v("Debug", "error: " + ex.getMessage(), ex);
        }
        catch (IOException ioe)
        {
             Log.v("Debug", "error: " + ioe.getMessage(), ioe);
        }


        try {
              inStream = new DataInputStream ( conn.getInputStream() );
              String str;
              Log.v("Debug","Server Response "+String.valueOf(inStream));
              while (( str = inStream.readLine()) != null)
              {
                   Log.v("Debug","Server Response "+str);
                   Toast.makeText(this, "Status: "+str, Toast.LENGTH_LONG).show();
              }
              inStream.close();
        }
        catch (IOException ioex)
        {
             Log.v("Debug", "error: " + ioex.getMessage(), ioex);
        }
      }
}

我还包括以下内容Uses Permissions:

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

日志猫:

09-23 12:26:15.676: I/ActivityManager(59): Starting activity: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=pack.coderzheaven/.UploadAudioDemo }
09-23 12:26:15.746: D/AndroidRuntime(522): Shutting down VM
09-23 12:26:15.746: D/dalvikvm(522): Debugger has detached; object registry had 1 entries
09-23 12:26:15.806: I/AndroidRuntime(522): NOTE: attach of thread 'Binder Thread #3' failed
09-23 12:26:21.627: I/ActivityManager(59): Starting activity: Intent { act=android.intent.action.CHOOSER cmp=android/com.android.internal.app.ChooserActivity (has extras) }
09-23 12:26:22.428: I/ActivityManager(59): Displayed activity android/com.android.internal.app.ChooserActivity: 659 ms (total 6698 ms)
09-23 12:26:24.247: I/ActivityManager(59): Starting activity: Intent { act=android.intent.action.GET_CONTENT typ=audio/* flg=0x3000000 cmp=com.android.music/.MusicPicker }
09-23 12:26:24.867: I/ActivityManager(59): Displayed activity com.android.music/.MusicPicker: 599 ms (total 599 ms)
09-23 12:26:27.427: D/AudioSink(34): bufferCount (4) is too small and increased to 12
09-23 12:26:27.652: W/AudioFlinger(34): write blocked for 83 msecs, 98 delayed writes, thread 0xb3d0
09-23 12:26:29.106: W/TimedEventQueue(34): Event 17 was not found in the queue, already cancelled?
09-23 12:26:29.276: I/System.out(507): SELECT_AUDIO
09-23 12:26:29.306: I/System.out(507): SELECT_AUDIO Path : /mnt/sdcard/download/tu_judda.mp3
09-23 12:26:34.986: D/dalvikvm(507): GC_FOR_MALLOC freed 4352 objects / 283128 bytes in 110ms
09-23 12:26:35.076: I/dalvikvm-heap(507): Grow heap (frag case) to 7.707MB for 5277339-byte allocation
09-23 12:26:35.256: D/dalvikvm(507): GC_FOR_MALLOC freed 1424 objects / 83568 bytes in 173ms
09-23 12:26:35.346: D/dalvikvm(507): GC_FOR_MALLOC freed 42 objects / 1888 bytes in 83ms
09-23 12:26:35.516: I/dalvikvm-heap(507): Grow heap (frag case) to 17.693MB for 10554880-byte allocation
09-23 12:26:35.696: D/dalvikvm(507): GC_FOR_MALLOC freed 0 objects / 0 bytes in 178ms
09-23 12:26:35.696: V/Debug(507): File is written
09-23 12:26:39.083: W/ActivityManager(59): Launch timeout has expired, giving up wake lock!
09-23 12:26:39.244: W/ActivityManager(59): Activity idle timeout for HistoryRecord{4504efe8 pack.coderzheaven/.UploadAudioDemo}
09-23 12:26:39.809: D/SntpClient(59): request time failed: java.net.SocketException: Address family not supported by protocol

我已经等了 25-30 分钟,但屏幕保持不变,文件都没有上传到服务器......

请帮忙..

4

1 回答 1

0

您还应该包括以下使用权限:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
于 2014-05-09T12:15:51.023 回答