Android中上传图片到服务端C#接收图

Android端

/* 上传文件至Server的方法 */
public static String uploadFile(String actionUrl, String newName, Bitmap bitmap){
    String end ="\r\n";
    String twoHyphens ="--";
    String boundary ="*****";
    try{
        URL url =new URL(actionUrl);
        HttpURLConnection con=(HttpURLConnection)url.openConnection();
      /* 允许InputOutput,不使用Cache */
        con.setDoInput(true);
        con.setDoOutput(true);
        con.setUseCaches(false);
      /* 设置传送的method=POST */
        con.setRequestMethod("POST");
      /* setRequestProperty */
        con.setRequestProperty("Connection", "Keep-Alive");
        con.setRequestProperty("Charset", "UTF-8");
        con.setRequestProperty("Content-Type",
                "multipart/form-data;boundary="+boundary);
      /* 设置DataOutputStream */
        DataOutputStream ds =
                new DataOutputStream(con.getOutputStream());
        ds.writeBytes(twoHyphens + boundary + end);
        ds.writeBytes("Content-Disposition: form-data; "+
                "name=\"file1\";"+"drawingName=\""+
                newName +"\""+ end);
        ds.writeBytes(end);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 80, baos);
        InputStream isBm = new ByteArrayInputStream(baos.toByteArray());
      /* 取得文件的FileInputStream */
       // FileInputStream fStream =new FileInputStream(uploadFile);
      /* 设置每次写入1024bytes */
        int bufferSize =1024;
        byte[] buffer =new byte[bufferSize];
        int length =-1;
      /* 从文件读取数据至缓冲区 */
        while((length = isBm.read(buffer)) !=-1){
        /* 将资料写入DataOutputStream */
            ds.write(buffer, 0, length);
        }
        ds.writeBytes(end);
        ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
      /* close streams */
        isBm.close();
        ds.flush();
      /* 取得Response内容 */
        InputStream is = con.getInputStream();
        int ch;
        StringBuffer b =new StringBuffer();
        while( ( ch = is.read() ) !=-1 ){
            b.append( (char)ch );
        }
      /* Response显示于Dialog */
      /* 关闭DataOutputStream */
        ds.close();
	//获取到的响应数据
        return b.toString();
    }
    catch(Exception e){
        return "";
    }
C#服务端

private String getPic(){//此方法名是Android端上传图片中接口地址中使用的
    //最主要的代码:HttpContext.Request.InputStream;获取Android中上传的字节流数据
    byte[] byts = new byte[HttpContext.Current.Request.InputStream.Length];
    HttpContext.Current.Request.InputStream.Read(byts, 0, byts.Length);
    string req = System.Text.Encoding.Default.GetString(byts);
    req = HttpContext.Current.Server.UrlDecode(req);
    return req;//返回给android
}



你可能感兴趣的:(android,c#,server,图片,string,Android,Studio)