ASP.NET MVC 接收Android上传的图片

从android端上传一张图片到 .NET MVC里时,如果你需要传入一些自定义参数(如上传者的ID)那么本文章将对你有用。

原理:图片以流的方式发送。参数用地址栏传址。

android端发送图片          :这里的Url是地址如:http://www.bqtalkthinsdg.com/Spdeak/saveImg?userId=13&imgName=xiaofeng"  file是你要上传图片。

public static void sendImg(String Url, File file) throws IOException {
		byte[] buf = new byte[1024];
		URL url = new URL(Url);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setReadTimeout(10 * 1000);
		conn.setConnectTimeout(10 * 1000);
		conn.setDoInput(true); // 允许输入流
		conn.setDoOutput(true); // 允许输出流
		conn.setUseCaches(false); // 不允许使用缓存
		conn.setRequestMethod("POST"); // 请求方式
		InputStream in = new FileInputStream(file);

		OutputStream osw = conn.getOutputStream();

		while (in.read(buf) != -1) {
			osw.write(buf);
		}

		osw.flush();
		osw.close();
		in.close();
		int code = conn.getResponseCode();
		System.out.println("code:" + code);
	}

ASP.NET MVC   获取参数时:用Request["参数名"]获取。这是我尝试多次后成功的。至少Request.Params的方式不能获取到。由于没转码,所以参数不能是中文。

 public void saveImg()
        {
            byte[] buffer = new byte[Request.InputStream.Length];
            Request.InputStream.Read(buffer, 0, buffer.Length);
            
            string path = "/img/lsj.jpg";
            FileStream fs = new FileStream(Server.MapPath(path), FileMode.Create, FileAccess.Write);
            BinaryWriter bw = new BinaryWriter(fs);
            bw.Write(buffer);
            bw.Close();
            fs.Close();
            string s2 = Request["userId"].ToString();
            string s3 = Request["imgName"].ToString();
            tb_user user2 = data.tb_user.Where(p => p.userId == 17).First();
            user2.userAddress = s2+s3;
            data.SubmitChanges();
        }

由于android+ASP.NET MVC的例子很少,所以很多东西都需要自己研究。如果你有更好的方式,记得告诉我哦!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值