最近经常用到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();
}
}