文件上传到Web服务器

1.添加需要的控件

  <form id="uploderform" method="post" action="fileupload.ashx" enctype="multipart/form-data"  runat="server" >

 文件名称:  <input type="file" id="myfile" runat="server" name="myfile">

                 <input type="button"  value="上 传"  id="fileupload" name="upload">

 </form >

2 ashx文件

 public void ProcessRequest (HttpContext context) {  

  •         HttpPostedFile _upfile = context.Request.Files["File1"];  
  •         if (_upfile == null)  
  •         {  
  •             ResponseWriteEnd(context, "4");//请选择要上传的文件   
  •         }  
  •         else  
  •         {  
  •             string fileName = _upfile.FileName;/*获取文件名: C:\Documents and Settings\Administrator\桌面\123.jpg*/  
  •             string suffix = fileName.Substring(fileName.LastIndexOf(".") + 1).ToLower();/*获取后缀名并转为小写: jpg*/  
  •             int bytes = _upfile.ContentLength;//获取文件的字节大小   
  •   
  •             if (suffix != "jpg")  
  •                 ResponseWriteEnd(context, "2"); //只能上传JPG格式图片   
  •             if (bytes > 1024 * 1024)  
  •                 ResponseWriteEnd(context, "3"); //图片不能大于1M   
  •   
  •             _upfile.SaveAs(HttpContext.Current.Server.MapPath("~/images/logo.jpg"));//保存图片   
  •             ResponseWriteEnd(context, "1"); //上传成功   
  •         }  
  •     }  
原文地址:https://www.cnblogs.com/linsu/p/2228554.html