Android的上传大文件 [英] Android Uploading large files

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

问题描述

我是pretty许多新的Andr​​oid开发,和我想的大小25的文件上传到50 MB到Web服务器,而我得到了内存不足的错误。我挣扎了近2天,不知道,我要去的地方错了。

上了车我要去的地方错了什么建议?

在code我的工作是

 私人的FileInputStream的FileInputStream = NULL;
私人诠释信息bytesAvailable,缓冲区大小,读取动作;
字节的buff [];
INT MAXBUFFERSIZE = 1 * 1024 * 1024;
字符串SERVER_URL =SERVER_URL;
DataOutputStream类DOS;
字符串构建器响应=新的String生成器();
绳体=边界值;
字符串body2 =边界值;
网址URL = NULL;
    尝试
    {
        URL =新的URL(SERVER_URL);
    }
    赶上(MalformedURLException的E1)
    {
        e1.printStackTrace();
    }    HttpURLConnection的康恩= NULL;
    尝试
    {
        康恩=(HttpURLConnection类)url.openConnection();
    }
    赶上(IOException异常E)
    {
        e.printStackTrace();
    }
    尝试
    {
        conn.setRequestMethod(POST);
        conn.setDoInput(真);
        conn.setDoOutput(真);
        conn.setRequestProperty(连接,保持活动);
        conn.setRequestProperty(内容类型,的multipart / form-data的;边界= A300x);
        conn.connect();
        DOS =新的DataOutputStream类(conn.getOutputStream());
        dos.writeBytes(体);
        inputfile文件=新的文件(的资源文件);
        的FileInputStream =新的FileInputStream(inputfile中);
        参考bytesAvailable = fileInputStream.available();
        缓冲区大小= Math.min(方bytesAvailable,MAXBUFFERSIZE);
        BUFF =新的字节[缓冲区大小]
        读取动作= fileInputStream.read(BUFF,0,缓冲区大小);
            而(读取动作大于0)
            {                dos.write(BUFF,0,缓冲区大小);
                dos.flush();
                参考bytesAvailable = fileInputStream.available();
                缓冲区大小= Math.min(方bytesAvailable,MAXBUFFERSIZE);
                读取动作= fileInputStream.read(BUFF,0,缓冲区大小);
            }
        fileInputStream.close();
        dos.write(\\ r \\ n.getBytes());
        dos.write(body2.getBytes());
        dos.flush();
        dos.close();
}
    赶上(的ProtocolException E)
    {
        // TODO自动生成catch块
        e.printStackTrace();
    }
    INT iresponse = 0;
    尝试
    {
        iresponse = conn.getResponse code();
    }
    赶上(IOException异常E)
    {
        // TODO自动生成catch块
        e.printStackTrace();
    }
    //的PrintStream(conn.getInputStream());    如果(iresponse == HttpURLConnection.HTTP_OK)
    {        BufferedReader中输入= NULL;
        尝试
        {
            输入=新的BufferedReader(新的InputStreamReader(conn.getInputStream()),8192);
        }
        赶上(IOException异常E1)
        {
            // TODO自动生成catch块
            e1.printStackTrace();
        }        串线= NULL;
        尝试
        {
            而((行= input.readLine())!= NULL)
                response.append(线);
        }
        赶上(IOException异常E)
        {
            // TODO自动生成catch块
            e.printStackTrace();
        }        尝试
        {
            input.close();
        }
        赶上(IOException异常E)
        {
            // TODO自动生成catch块
            e.printStackTrace();
        }
    }
    返回response.toString();


解决方案

这可能会有帮助。

 私人无效uploadFile(档案文件)抛出IOException
    Log.i(TAG,上传+文件);
    字符串videoName = file.getParentFile()的getName()。    AndroidHttpClient的HttpClient = AndroidHttpClient.newInstance(GoProLive.TAG);
    尝试{
        HttpConnectionParams.setConnectionTimeout(httpclient.getParams(),ConnectTimeout);
        HttpConnectionParams.setSoTimeout(httpclient.getParams(),DataTimeout);
        HttpPost后=新HttpPost(
                的String.format(HTTP://+服务器名称+/上传/%S /%S,user.getUsername(),file.getName()));
        post.setEntity(新FileEntity(文件,应用程序/八位字节流));        SimpleDateFormat的DF =(的SimpleDateFormat)SimpleDateFormat.getDateTimeInstance(SimpleDateFormat.SHORT,SimpleDateFormat.SHORT,Locale.US);
        df.applyPattern(EEE,DD MMM YYYY HH:MM:SS Z);
        post.setHeader(上次修改,df.format(新日期(file.lastModified())));
        HTT presponse HTT presponse = executePost(HttpClient的,后);
        INT状态code = HTT presponse.getStatusLine()的getStatus code()。
        如果(状态code == HttpStatus.SC_OK){
            file.delete();
        }其他{
            抛出新的HttpException(无法上传文件+ file.getAbsolutePath(),状态code);
        }
    } {最后
        httpclient.close();
    }
}

I am pretty much new to android development, and I am trying to upload a file of size 25 to 50 MB to a web server, and am getting the out of memory error. I am struggling for past 2 days and have no clue, where I am going wrong.

Got any suggestions on where I am going wrong?

The code I am working on is

private FileInputStream fileInputStream = null;
private int bytesavailable,buffersize,bytesRead ;
byte buff[];
int maxBufferSize = 1*1024*1024;
String server_url ="server_url";
DataOutputStream dos;
String Builder response = new String Builder();
String body = "boundary values";
String body2 = "Boundary values";
URL url = null;
    try 
    {
        url = new URL(server_url);
    } 
    catch (MalformedURLException e1) 
    {
        e1.printStackTrace();
    }

    HttpURLConnection conn = null;
    try 
    {
        conn = (HttpURLConnection) url.openConnection();
    } 
    catch (IOException e) 
    {
        e.printStackTrace();
    }
    try 
    {
        conn.setRequestMethod("POST");
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setRequestProperty("Connection","Keep-Alive");
        conn.setRequestProperty("Content-Type","multipart/form-data; boundary=A300x");
        conn.connect();
        dos = new DataOutputStream(conn.getOutputStream());
        dos.writeBytes(body);
        File inputfile = new File(sourceFile);
        fileInputStream = new FileInputStream(inputfile);


        bytesavailable = fileInputStream.available();
        buffersize = Math.min(bytesavailable, maxBufferSize);
        buff = new byte[buffersize];
        bytesRead = fileInputStream.read(buff, 0, buffersize);


            while (bytesRead > 0) 
            {

                dos.write(buff, 0, buffersize);
                dos.flush();
                bytesavailable = fileInputStream.available();
                buffersize = Math.min(bytesavailable, maxBufferSize);
                bytesRead = fileInputStream.read(buff, 0, buffersize);
            }
        fileInputStream.close();
        dos.write("\r\n".getBytes());
        dos.write(body2.getBytes());
        dos.flush();
        dos.close();
} 
    catch (ProtocolException e) 
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    int iresponse = 0;
    try 
    {
        iresponse = conn.getResponseCode();
    } 
    catch (IOException e) 
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    //printStream(conn.getInputStream());

    if (iresponse == HttpURLConnection.HTTP_OK) 
    {

        BufferedReader input = null;
        try 
        {
            input = new BufferedReader(new InputStreamReader(conn.getInputStream()), 8192);
        } 
        catch (IOException e1) 
        {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        String line = null;
        try 
        {
            while ((line = input.readLine()) != null)
                response.append(line);
        } 
        catch (IOException e) 
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        try 
        {
            input.close();
        } 
        catch (IOException e) 
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }


    return response.toString();

解决方案

This may be helpful.

private void uploadFile(File file) throws IOException {
    Log.i(TAG, "Uploading " + file);
    String videoName = file.getParentFile().getName();

    AndroidHttpClient httpclient = AndroidHttpClient.newInstance(GoProLive.TAG);
    try {
        HttpConnectionParams.setConnectionTimeout(httpclient.getParams(), ConnectTimeout);
        HttpConnectionParams.setSoTimeout(httpclient.getParams(), DataTimeout);
        HttpPost post = new HttpPost(
                String.format("http://" + ServerName + "/upload/%s/%s", user.getUsername(), file.getName()));
        post.setEntity(new FileEntity(file, "application/octet-stream"));

        SimpleDateFormat df = (SimpleDateFormat) SimpleDateFormat.getDateTimeInstance(SimpleDateFormat.SHORT, SimpleDateFormat.SHORT, Locale.US);
        df.applyPattern("EEE, dd MMM yyyy HH:mm:ss z");
        post.setHeader("Last-Modified", df.format(new Date(file.lastModified())));
        HttpResponse httpResponse = executePost(httpclient, post);
        int statusCode = httpResponse.getStatusLine().getStatusCode();
        if (statusCode == HttpStatus.SC_OK) {
            file.delete();
        } else {
            throw new HttpException("Failed to upload file " + file.getAbsolutePath(), statusCode);
        }
    } finally {
        httpclient.close();
    }
}

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

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