c# 发送http请求 到 servlet 跨平台 上传图像文件

本文介绍如何使用C#通过HTTP请求将文件流发送到Servlet,实现跨平台的图像文件上传。C#代码负责获取文件并转换为请求流,Servlet接收流并生成文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近经常用到c# 遇到一个需求。 由c#发送http请求流 到 servlet 接收文件流生成图片。  


原理: c# 获取文件  ---> 转化请求流 ---> 发送post提交 ----> servlet 接收输入流  --->生成文件


c#代码

 String fileToUpload = "E:\\father.jpg";
            //要发送请求的地址
            String uploadUrl = "http://localhost:8080/NewSoft/MediaServlet";

            HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(uploadUrl);
            webrequest.Method = "POST";

            FileStream fileStream = new FileStream(fileToUpload, FileMode.Open, FileAccess.Read);
            webrequest.ContentLength = fileStream.Length;
            Stream requestStream = webrequest.GetRequestStream();
            //requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);

            byte[] buffer = new Byte[(int)fileStream.Length];
            int bytesRead = 0;
            while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                requestStream.Write(buffer, 0, bytesRead);
            //requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
            requestStream.Close();

            Console.ReadKey();

servlet代码


public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//String path = request.getRealPath("/");
		String path = "E:\\";

        try {
            File file_path = new File(path);
            if (!file_path.exists()) {
                file_path.mkdirs();
            }
            InputStream fin = request.getInputStream();
            //System.out.println("key :"+ fin.read());
            String file_path_name =path +(int)(Math.random()*1000)+".jpg";
            //System.out.println("file_path_name:"+file_path_name);
            File file = new File(file_path_name);
            FileOutputStream file_out = new FileOutputStream(file);
            int b;
            while ((b = fin.read()) != -1) {
                file_out.write(b);
            }
            fin.close();
            file_out.close();
        } catch (Exception e) {
           e.printStackTrace();
        }
	
	}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值