Streaming file from android to .net http service

2019-07-29 01:29发布

Im trying to stream a file from android to an asp.net service:

private static void writeFile(File file, DataOutputStream out)
        throws IOException {

    BufferedInputStream bufferedFileIs = null;
    Base64OutputStream base64out = null;
    try {
        out.writeBytes("fileBase64=");
        base64out = new Base64OutputStream(out, Base64.DEFAULT);

        FileInputStream fileIs = new FileInputStream(file);
        bufferedFileIs = new BufferedInputStream(fileIs);
        int nextByte;
        while ((nextByte = bufferedFileIs.read()) != -1) {
            base64out.write(nextByte);
        }
    } finally {
        if (bufferedFileIs != null) {   
            bufferedFileIs.close();
        }
        if(base64out != null)
            base64out.flush();

    }

}

and receive it like this

String base64 = Request.Form["fileBase64"];

byte[] bytes = System.Convert.FromBase64String(base64);

I use an HttpURLConnection and I dont get any exceptions but the received file(image) is corrupted in the process. I tried ALOT of different stream wrapper pairs, but no luck. Anyone have experience in this? I stream other form entries in the same connection and these arrive un-corrupted, for example

&UserID=12345

Gratefull for your help.

Cheers!

1条回答
劳资没心,怎么记你
2楼-- · 2019-07-29 01:47

Solved it:

Prepare the file:

File file = new File(LocalFilePath);

FileEntity fileentity = new FileEntity(file, "UTF-8");
HttpUtilities.postRequest(WebServiceURL, fileentity);

post the request:

public static String postRequest(String url, HttpEntity aEntity)
        throws IOException {

    InputStream is = null;
    try {

        HttpClient client = new DefaultHttpClient();

        HttpPost httppost = new HttpPost(url);

        httppost.setEntity(aEntity);

        HttpResponse response = client.execute(httppost);
        HttpEntity responseEntity = response.getEntity();

        is = responseEntity.getContent();

    } catch (Exception e) {
    }

    return getResponse(is);
}

after this the webserver complained:

HttpException (0x80004005): Maximum request length exceeded

max request-length defaults to 4mb so i set this in web.config:

<system.web>
    <httpRuntime maxRequestLength="1048576"/>
</system.web

Which allows files up to 1GB(!).

edit:

Forgot the server code:

var str = Request.InputStream;
strLen = Convert.ToInt32(str.Length);
byte[] strArr = new byte[strLen];
strRead = str.Read(strArr, 0, strLen);
查看更多
登录 后发表回答