如何将文件(视频,图像和音频)从Android发送到ASP.NET?

时间:2013-06-14 00:09:13

标签: android asp.net file-upload

我一直在尝试将文件(特别是图片,视频和音频)从我的Android应用程序发送到ASP.NET服务器(它是一个ASP.NET服务器,我见过很多php实现但没有ASP .NET)

我尝试使用FileInputStream,Multipart等发送它们 主要问题是,我只是无法弄清楚如何接收(也许还有发送部分未正确实现:S)服务器端的文件:( 你能告诉我这是怎么做到的吗?

而且,你能告诉我使用Miltipart或FileInputStream之间的区别

最后,作为一个加号:),如何在连接丢失后恢复上传?

非常感谢你!!!!

1 个答案:

答案 0 :(得分:0)

对于上传文件,您可以创建一个线程/异步,如: 公共类HttpFileUploader {

private static final String TAG = "HttpFileUploader";

private URL connectURL;
private Map<String, String> params;
// private String responseString;
private String fileName, photoParamName;
// private byte[] dataToServer;
private FileInputStream fileInputStream = null;
String responce = "";

public HttpFileUploader(Map<String, String> params, String photoParamName,
        String fileName, String urlString) {
    try {
        System.out.println(urlString);
        connectURL = new URL(urlString);


    } catch (Exception ex) {
        Log.i(TAG, "MALFORMATED URL");
    }
    this.params = params;
    this.fileName = fileName;
    this.photoParamName = photoParamName;
}

/**
 * Starts uploading.
 * 
 * @throws FileNotFoundException
 */
public String doStart() throws FileNotFoundException {
    fileInputStream = new FileInputStream(new File(fileName));
    thirdTry();

    return responce;
}

private void thirdTry() {
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "**lx90l39slks02klsdfaksd2***";
    try {
        // ------------------ CLIENT REQUEST

        // Open a HTTP connection to the URL

        HttpURLConnection conn = (HttpURLConnection) connectURL
                .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);

        DataOutputStream dos = new DataOutputStream(conn.getOutputStream());

        // add the params to the form data
        if (params != null) {
            for (Entry<String, String> entry : params.entrySet()) {
                // Log.d(TAG, "submitting param "
                // + entry.getKey() + " : " + entry.getValue());
                dos.writeBytes(twoHyphens + boundary + lineEnd);
                dos.writeBytes("Content-Disposition: form-data; name=\""
                        + entry.getKey() + "\"" + lineEnd);
                dos.writeBytes(lineEnd);
                dos.writeBytes(entry.getValue());
                dos.writeBytes(lineEnd);
            }
        }

        // Log.d(TAG, "submitting image " + photoParamName
        // + " : " + fileName);
        // add image to the form data
        dos.writeBytes(twoHyphens + boundary + lineEnd);
        if (photoParamName == null)
            photoParamName = "photo";
        dos.writeBytes("Content-Disposition: form-data;name=\""
                + photoParamName + "\";filename=\"" + photoParamName + "\""
                + lineEnd);
        dos.writeBytes("Content-Type: image/jpeg" + lineEnd);
        dos.writeBytes(lineEnd);

        // upload image

        // create a buffer of maximum size

        int bytesAvailable = fileInputStream.available();
        int maxBufferSize = 1024;
        int bufferSize = Math.min(bytesAvailable, maxBufferSize);
        byte[] buffer = new byte[bufferSize];

        // read file and write it into form...

        int 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.d(TAG, "File (" + fileName + ") is written");
        fileInputStream.close();
        dos.flush();

        InputStream is = conn.getInputStream();
        // retrieve the response from server
        int ch;

        StringBuffer b = new StringBuffer();
        while ((ch = is.read()) != -1) {
            b.append((char) ch);
        }
        String s = b.toString();
        responce = s;
        Log.i(TAG, "Response =" + s);
        dos.close();

    } catch (MalformedURLException ex) {
        Log.e(TAG, "error URL: " + ex.getMessage(), ex);
    } catch (IOException ioe) {
        Log.e(TAG, "error IO: " + ioe.getMessage(), ioe);
    }
}

}

上传成功后,如果通过检查网络连接在几次重试后上传时,web api必须返回成功响应(如果未完成/例外)。您也可以启动计时器以重做任务。