0

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

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

另外,你能告诉我使用 Miltipart 或 FileInputStream 有什么区别吗?

最后,作为一个加号:),我怎样才能在连接丢失后恢复上传?

非常感谢你!!!!

4

1 回答 1

0

对于上传文件,您可以创建一个线程/异步,例如: public class 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 必须返回成功响应,如果它没有完成/异常,则在通过检查网络连接重试几次后上传时出现异常。您还可以启动计时器以重做任务。

于 2013-06-14T03:25:28.713 回答