文件中的Andr​​oid上传到服务器 [英] Android Upload of File to Server

查看:71
本文介绍了文件中的Andr​​oid上传到服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基于的previous文章中,我试图用<一个建议

href="http://stackoverflow.com/questions/12789703/android-uploading-image-on-server-with-php">Android:在服务器上用PHP 上传图片,但是我得到一个文件,未发现异常。

下面是我的作为在上面的描述后功能。我输入它们是:

画廊:uploadFile:源文件不存在:内容://媒体/外部/图片/媒体/ 342 图文:uploadFile:源文件不存在:文件:///存储/模拟/ 0 / MYDIR /等等

这些URI的源自一个lanched到catputre /选择它们的意图。为什么我得到一个找不到文件例外任何想法?

 私人无效doFileUpload(字符串exsistingFileName){
    HttpURLConnection的康恩= NULL;
    DataOutputStream类DOS = NULL;
    inStream中的DataInputStream = NULL;

    //字符串exsistingFileName =/sdcard/six.3gp;
    //这是这个地方是你做错了什么。

    字符串lineEnd =\ r \ N的;
    串twoHyphens = - ;
    字符串边界=*****;
    INT读取动作,方bytesAvailable,缓冲区大小;
    byte []的缓冲区;
    INT maxBufferSize = 1 * 1024 * 1024;
    字符串urlString =htt​​p://192.168.1.5/upload.php;
    尝试
    {
        Log.e(MediaPlayer的,内部第二种方法);
        的FileInputStream的FileInputStream =新的FileInputStream(新文件(exsistingFileName));
        网址URL =新的URL(urlString);
        康恩=(HttpURLConnection类)url.openConnection();
        conn.setDoInput(真正的);
        //允许输出
        conn.setDoOutput(真正的);
        //不要使用缓存副本。
        conn.setUseCaches(假);
        //使用POST方法。
        conn.setRequestMethod(POST);
        conn.setRequestProperty(连接,保持活动);
        conn.setRequestProperty(内容类型,多部分/格式数据;边界=+界);
        DOS =新DataOutputStream类(conn.getOutputStream());
        dos.writeBytes(twoHyphens +边界+ lineEnd);
        dos.writeBytes(内容处置:表格数据;名称= \UploadedFile的\;文件名= \+ exsistingFileName +\+ lineEnd);
        dos.writeBytes(lineEnd);
        Log.e(MediaPlayer的,头信息);
        方bytesAvailable = fileInputStream.available();
        BUFFERSIZE = Math.min(方bytesAvailable,maxBufferSize);
        缓冲区=新的字节[BUFFERSIZE]
        读取动作= fileInputStream.read(缓冲液,0,BUFFERSIZE);
        而(读取动作大于0)
        {
            dos.write(缓冲液,0,BUFFERSIZE);
            方bytesAvailable = fileInputStream.available();
            BUFFERSIZE = Math.min(方bytesAvailable,maxBufferSize);
            读取动作= fileInputStream.read(缓冲液,0,BUFFERSIZE);
        }
        dos.writeBytes(lineEnd);
        dos.writeBytes(twoHyphens +边界+ twoHyphens + lineEnd);
        的BufferedReader在=新的BufferedReader(新的InputStreamReader(conn.getInputStream()));
        字符串inputLine;
        字符串LogString =;

        而((inputLine = in.readLine())!= NULL){
            LogString = LogString + inputLine;
        }

        Log.i(Utils.TAG,LogString);
        //关闭流
        fileInputStream.close();
        dos.flush();
        dos.close();
    }
    赶上(MalformedURLException的前)
    {
        Log.e(MediaPlayer的,错误:+ ex.getMessage(),前);
    }
    赶上(IOException异常IOE)
    {
        Log.e(MediaPlayer的,错误:+ ioe.getMessage(),IOE);
    }

    // ------------------读取服务器响应
    尝试 {
        inStream中=新的DataInputStream(conn.getInputStream());
        字符串str;
        而((海峡= inStream.readLine())!= NULL)
        {
            Log.e(MediaPlayer的,服务器响应+ STR);
        }
        / *而((海峡= inStream.readLine())!= NULL){

        } * /
        inStream.close();
    }
    赶上(IOException异常ioex){
        Log.e(MediaPlayer的,错误:+ ioex.getMessage(),ioex);
    }
}
 

解决方案
  

我得到一个文件未找到异常

这是因为这两个时间都不路径文件。你可以告诉看着他们。您还没有从我的previous答案。

替换:

 的FileInputStream的FileInputStream =新的FileInputStream(新文件(exsistingFileName));
 

 的InputStream contentInputStream = getContentResolver()openInputStream(Uri.parse(exsistingFileName))。
 

(和替换出现的的FileInputStream contentInputStream 为你的方法的其余部分)

需要注意的是:

  • 这假设你的 doFileUpload()的一些类,它继承上下文,这样的实现作为活动服务。您将需要安排获得 ContentResolver的 doFileUpload()通过其他方式,如果 doFileUpload ()没有获得 getContentResolver()

  • 您可以简化问题有点通过传递乌里您接收到 doFileUpload(),而不是将其转换为字符串,然后回一个乌里

  • 您将需要创造自己的文件名内容处置:的头,因为你没有得到的文件名乌里

Based on the recommendations of a previous post I'm trying to use Android: Uploading image on server with php however I get a file not found exception.

Here's my function as described in the post above. My input for these are:

Gallery: uploadFile: Source File not exist :content://media/external/images/media/342 Photo: uploadFile: Source File not exist: file:///storage/emulated/0/MyDir/blah

These uri's are derived from the intent a lanched to catputre/select them. Any ideas why I get a File Not Found exception?

private void doFileUpload(String exsistingFileName){
    HttpURLConnection conn = null;
    DataOutputStream dos = null;
    DataInputStream inStream = null; 

    //String exsistingFileName = "/sdcard/six.3gp";
    // Is this the place are you doing something wrong.

    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary =  "*****";
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1*1024*1024;
    String urlString = "http://192.168.1.5/upload.php";
    try
    {
        Log.e("MediaPlayer","Inside second Method");
        FileInputStream fileInputStream = new FileInputStream(new File(exsistingFileName) );
        URL url = new URL(urlString);
        conn = (HttpURLConnection) url.openConnection();
        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=\"" + exsistingFileName +"\"" + lineEnd);
        dos.writeBytes(lineEnd);
        Log.e("MediaPlayer","Headers are written");
        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);
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String inputLine;
        String LogString = "";

        while ((inputLine = in.readLine()) != null)  {
            LogString= LogString + inputLine;
        }

        Log.i(Utils.TAG, LogString);
        // close streams
        fileInputStream.close();
        dos.flush();
        dos.close();
    }
    catch (MalformedURLException ex)
    {
        Log.e("MediaPlayer", "error: " + ex.getMessage(), ex);
    }
    catch (IOException ioe)
    {
        Log.e("MediaPlayer", "error: " + ioe.getMessage(), ioe);
    }

    //------------------ read the SERVER RESPONSE
    try {
        inStream = new DataInputStream ( conn.getInputStream() );
        String str;            
        while (( str = inStream.readLine()) != null)
        {
            Log.e("MediaPlayer","Server Response"+str);
        }
        /*while((str = inStream.readLine()) !=null ){

        }*/
        inStream.close();
    }
    catch (IOException ioex){
        Log.e("MediaPlayer", "error: " + ioex.getMessage(), ioex);
    }
}

解决方案

i get a file not found exception

That is because neither of those are paths to files. You can tell that by looking at them. You also did not follow the instructions from my previous answer.

Replace:

FileInputStream fileInputStream = new FileInputStream(new File(exsistingFileName) );

with:

InputStream contentInputStream = getContentResolver().openInputStream(Uri.parse(exsistingFileName));

(and replace occurrences of fileInputStream with contentInputStream for the rest of your method)

Note that:

  • This assumes that your doFileUpload() is implemented on some class that inherits from Context, such as an Activity or a Service. You will need to arrange to get a ContentResolver to doFileUpload() by other means if doFileUpload() does not have access to getContentResolver().

  • You could simplify matters a bit by passing in the Uri you received into doFileUpload(), rather than converting it to a String and then back into a Uri.

  • You will need to invent your own filename for the Content-Disposition: header, as you do not get a filename from the Uri.

这篇关于文件中的Andr​​oid上传到服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆