简体   繁体   English

Android图片上传问题

[英]Android image Upload problem

Hello i am wanting to upload image from android emulator to asp.net server. 您好我想将图像从android模拟器上传到asp.net服务器。 The code below can communicate the server. 下面的代码可以与服务器通信。 When I tried to create a text file to see the data sent from android was successful or not . 当我试图创建一个文本文件,看看从android发送的数据是否成功。 But no the file data didn't send across to the server. 但是没有文件数据没有发送到服务器。 I tried sending the plain text to the server but the file I created on the server didn't print the text. 我尝试将纯文本发送到服务器,但我在服务器上创建的文件没有打印文本。

The code here: HttpURLConnection conn = null; 这里的代码:HttpURLConnection conn = null;

    String boundary = "==============";

        try
        {   
            String disposition = "Content-Disposition: form-data; name=\"userfile\"; filename=\"" + filename + ".jpg\"";
            String contentType = "Content-Type: application/octet-stream";

            String t1   = "Content-Disposition: form-data; name=\"test\";";
            String t2 = "Content-Type: text/plain";

            // This is the standard format for a multipart request
            StringBuffer requestBody = new StringBuffer();
            /*
            requestBody.append("--"+boundary);
            requestBody.append('\n');
            requestBody.append(disposition);
            requestBody.append('\n');
            requestBody.append(contentType);
            requestBody.append('\n');
            requestBody.append('\n');
            requestBody.append(new String(getByteFromStream(stream)));
            */

            requestBody.append('\n');
            requestBody.append('\n');
            requestBody.append("--"+boundary);
            requestBody.append('\n');
            requestBody.append(t1);
            requestBody.append('\n');
            requestBody.append(t2);
            requestBody.append('\n');
            requestBody.append('\n');
            requestBody.append("basdfsdafsadfsad");
            requestBody.append("--"+boundary+"--");

            // Make a connect to the server
            URL url = new URL(targetURL);
            conn = (HttpURLConnection) url.openConnection();

            // Put the authentication details in the request
           /*
             if (username != null) {

                String usernamePassword = username + ":" + password;
                String encodedUsernamePassword = Base64.encodeBytes(usernamePassword.getBytes());
                conn.setRequestProperty ("Authorization", "Basic " + encodedUsernamePassword);
            }
            */
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("MIME-Version:", "1.0");
            conn.setRequestProperty("Content-Type", "multipart/mixed; boundary=" + boundary);

            // Send the body
            DataOutputStream dataOS = new DataOutputStream(conn.getOutputStream());
            dataOS.writeBytes(requestBody.toString());
            dataOS.flush();
            dataOS.close();

            // Ensure we got the HTTP 200 response code
            int responseCode = conn.getResponseCode();
            if (responseCode != 200) {
                throw new Exception(String.format("Received the response code %d from the URL %s", responseCode, url));
            }

Is my request body layout not correctly ? 我的请求正文布局不正确吗?

I am using asp.net for as file handler. 我使用asp.net作为文件处理程序。 Below is the simple Android code for the event you will use to upload the file 以下是您将用于上传文件的事件的简单Android代码

    String pathToOurFile = "/mnt/sdcard/sysdroid.png";//this will be the file path        String urlServer = "http://yourdomain/fileupload.aspx";
int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1*1024*1024;

    try
    {
    FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile) );

    URL url = new URL(urlServer);
    connection = (HttpURLConnection) url.openConnection();

    // Allow Inputs & Outputs
    connection.setDoInput(true);
    connection.setDoOutput(true);
    connection.setUseCaches(false);

    // Enable POST method
    connection.setRequestMethod("POST");

    connection.setRequestProperty("Connection", "Keep-Alive");
    connection.setRequestProperty("Content-Type",  "multipart/form-data");
    connection.setRequestProperty("SD-FileName", "sysdroid.png");//This will be the file name

    outputStream = new DataOutputStream( connection.getOutputStream() );
    bytesAvailable = fileInputStream.available();
    bufferSize = Math.min(bytesAvailable, maxBufferSize);
    buffer = new byte[bufferSize];

    // Read file
    bytesRead = fileInputStream.read(buffer, 0, bufferSize);

    while (bytesRead > 0)
    {
        outputStream.write(buffer, 0, bufferSize);
        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
    }

     int serverResponseCode = connection.getResponseCode();
     String serverResponseMessage = connection.getResponseMessage();
     Log.d("ServerCode",""+serverResponseCode);
     Log.d("serverResponseMessage",""+serverResponseMessage);
    fileInputStream.close();
    outputStream.flush();
    outputStream.close();


}
    catch (Exception ex)
    {
        //ex.printStackTrace();
        Log.e("Error: ", ex.getMessage());
    }

So far so good. 到现在为止还挺好。 Lets look into the asp.net code. 让我们看看asp.net代码。 I used simple 'Web Form' for this. 我为此使用了简单的“Web表单”。 The code behind is 背后的代码是

protected void Page_Load(object sender, EventArgs e)
{
    string uploadDir = Server.MapPath("~/images");
    string imgPath = Path.Combine(uploadDir, Request.Headers["SD-FileName"]);

    try{          
        byte[]bytes = new byte[Request.InputStream.Length];
        Request.InputStream.Read(bytes, 0, bytes.Length);
        System.IO.MemoryStream ms = new System.IO.MemoryStream(bytes);
        Bitmap btMap = (Bitmap)System.Drawing.Image.FromStream(ms);
        btMap.Save(imgPath, ImageFormat.Jpeg);
        ms.Close();
    }
    catch (Exception exp)
    {            
        Response.Write(exp.Message);
    }     
}

Hope this will work and you have the knowledge of read/write permissions on both Android's SD card and asp.net folders. 希望这会起作用,你对Android的SD卡和asp.net文件夹都有读/写权限的知识。

cheers Fahar 欢呼法哈尔

Because you upload two files, so you should see the last format. 因为您上传了两个文件,所以您应该看到最后一种格式。 Good luck for you. 祝你好运。 6. Examples 6.例子

Suppose the server supplies the following HTML: 假设服务器提供以下HTML:

 <FORM ACTION="http://server.dom/cgi/handle"
       ENCTYPE="multipart/form-data"
       METHOD=POST>
 What is your name? <INPUT TYPE=TEXT NAME=submitter>
 What files are you sending? <INPUT TYPE=FILE NAME=pics>
 </FORM>

and the user types "Joe Blow" in the name field, and selects a text file "file1.txt" for the answer to 'What files are you sending?' 并且用户在名称字段中键入“Joe Blow”,并选择文本文件“file1.txt”作为“您要发送什么文件?”的答案。

The client might send back the following data: 客户端可能会发回以下数据:

    Content-type: multipart/form-data, boundary=AaB03x

    --AaB03x
    content-disposition: form-data; name="field1"

    Joe Blow
    --AaB03x
    content-disposition: form-data; name="pics"; filename="file1.txt"
    Content-Type: text/plain

     ... contents of file1.txt ...
    --AaB03x--

If the user also indicated an image file "file2.gif" for the answer to 'What files are you sending?', the client might client might send back the following data: 如果用户还为“您要发送什么文件?”的答案指示了图像文件“file2.gif”,则客户端可能会向客户端发回以下数据:

    Content-type: multipart/form-data, boundary=AaB03x

    --AaB03x
    content-disposition: form-data; name="field1"

    Joe Blow
    --AaB03x
    content-disposition: form-data; name="pics"
    Content-type: multipart/mixed, boundary=BbC04y

    --BbC04y
    Content-disposition: attachment; filename="file1.txt"
    Content-Type: text/plain

    ... contents of file1.txt ...
    --BbC04y
    Content-disposition: attachment; filename="file2.gif"
    Content-type: image/gif
    Content-Transfer-Encoding: binary

      ...contents of file2.gif...
    --BbC04y--
    --AaB03x--

Form-based File Upload in HTML HTML格式的基于表单的文件上载

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM