C# 编程WinForm 上传文件到 Asp.Net 的 Web项目
在做WinForm时,需要WinForm同Web进行交互,有时需要进行图片、文件的上传操作.
WinForm的代码如下:
private void button2_Click(object sender, EventArgs e)
{
// string a = MyUploader(this.textBox1.Text.Trim(), @"http://localhost:4451/TEST/Default.aspx");
string a = MyUploader(this.textBox1.Text.Trim(), @"http://localhost/release/Default.aspx");
MessageBox.Show(a);
}
public static string MyUploader(string strFileToUpload, string strUrl)
{
string strFileFormName = "file";
Uri oUri = new Uri(strUrl);
string strBoundary = "----------" + DateTime.Now.Ticks.ToString("x");
// The trailing boundary string
byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + strBoundary + "\r\n");
// The post message header
StringBuilder sb = new StringBuilder();
sb.Append("--");
sb.Append(strBoundary);
sb.Append("\r\n");
sb.Append("Content-Disposition: form-data; name=\"");
sb.Append(strFileFormName);
sb.Append("\"; filename=\"");
sb.Append(Path.GetFileName(strFileToUpload));
sb.Append("\"");
sb.Append("\r\n");
sb.Append("Content-Type: ");
sb.Append("application/octet-stream");
sb.Append("\r\n");
sb.Append("\r\n");
string strPostHeader = sb.ToString();
byte[] postHeaderBytes = Encoding.UTF8.GetBytes(strPostHeader);
// The WebRequest
HttpWebRequest oWebrequest = (HttpWebRequest)WebRequest.Create(oUri);
oWebrequest.ContentType = "multipart/form-data; boundary=" + strBoundary;
oWebrequest.Method = "POST";
// This is important, otherwise the whole file will be read to memory anyway...
oWebrequest.AllowWriteStreamBuffering = false;
// Get a FileStream and set the final properties of the WebRequest
FileStream oFileStream = new FileStream(strFileToUpload, FileMode.Open, FileAccess.Read);
long length = postHeaderBytes.Length + oFileStream.Length + boundaryBytes.Length;
oWebrequest.ContentLength = length;
Stream oRequestStream = oWebrequest.GetRequestStream();
// Write the post header
oRequestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
// Stream the file contents in small pieces (4096 bytes, max).
byte[] buffer = new Byte[checked((uint)Math.Min(4096, (int)oFileStream.Length))];
int bytesRead = 0;
while ((bytesRead = oFileStream.Read(buffer, 0, buffer.Length)) != 0)
oRequestStream.Write(buffer, 0, bytesRead);
oFileStream.Close();
// Add the trailing boundary
oRequestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
WebResponse oWResponse = oWebrequest.GetResponse();
Stream s = oWResponse.GetResponseStream();
StreamReader sr = new StreamReader(s);
String sReturnString = sr.ReadToEnd();
Console.WriteLine(sReturnString);
// Clean up
oFileStream.Close();
oRequestStream.Close();
s.Close();
sr.Close();
return sReturnString;
}
在按钮点击时,便会触发提交操作,Web的Default.aspx代码如下:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Files.Count > 0)
{
try
{
HttpPostedFile file = Request.Files[0];
string filePath = this.MapPath("FileUpload") + "\\" + file.FileName;
file.SaveAs(filePath);
Response.Write("成功了");
}
catch (Exception)
{
Response.Write("失败了1");
}
}
else
{
Response.Write("失败了2");
}
Response.End();
}
}
这样,便可以将文件通过winform 上传到web 服务器上。
如果服务器端是Java的Web,则可以借助SmartUpload组件,Java端上传的Servlet如下:
package com.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.jspsmart.upload.Files;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;
public class UpLoad extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
SmartUpload mySmartUpload = new SmartUpload();
mySmartUpload.initialize(getServletConfig(), request, response);
mySmartUpload.upload();
Files files = mySmartUpload.getFiles();
int num = files.getCount();
for (int i = 0; i < num; i++) {
com.jspsmart.upload.File myfile = files.getFile(i);
String fileName = myfile.getFileName();
fileName = new String(fileName.getBytes(), "UTF-8");//强转成UTF8不然中文文件名会是乱码
myfile.saveAs("/upload/" + fileName, i + 1);
}
String ret = "OK";
byte[] rep = ret.getBytes();
response.getOutputStream().write(rep);
} catch (SmartUploadException e) {
e.printStackTrace();
}
}
}
至此,WinForm上传文件到Web项目,服务器端为.Net和Java的,均可以使用。
是不是少包呀,Java Web是很简单的一个。
请问能不能把服务器端是Java的Web传我一下啊?我把代码复制到eclipse有报错。。我邮箱是578617577@qq.com