不废话,直接上代码。
save.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="save.aspx.cs" Inherits="save" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>上传文件测试</title>
<script language="javascript" type="text/javascript">
// <![CDATA[
function Button1_onclick() {
document.getElementById("form1").submit();
}
// ]]>
</script>
</head>
<body>
<form id="form2" runat="server">
<input id="File2" type="file" runat="server" />
<asp:Button ID="Button2" runat="server" Text="纯服务器端上传" />
</form>
<form id="form1" action="save.aspx" method="post" enctype="multipart/form-data">
<input id="File1" name="File1" type="file" />
<input id="Button1" type="button" value="脚本控制上传" οnclick="Button1_onclick()" /><br />
</form>
<form id="form4" method="post" enctype="multipart/form-data" action="save.aspx">
<input id="testId" type="file" name="testName" />
<input id="testSubmit" type="submit" value="纯客户端上传" />
</form>
</body>
</html>
save.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
public partial class save : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(Request.Files.Count.ToString());
if (Request.Files.Count > 0)
{
this.save_file();
}
}
private void save_file()
{
HttpPostedFile file = Request.Files[0];
Response.Write(file.FileName);
file.SaveAs(Server.MapPath(Path.GetFileName(file.FileName)));
}
}
form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
WebClient myWebClient = new WebClient();
byte[] result=myWebClient.UploadFile("http://localhost:1503/net4_test/save.aspx",
"POST",
@"D:/t.jpg");
}
}
}
这样就实现了页面、winform窗口上传图片。