首页 > 编程 > ASP > 正文

使aspx页面能接受HTML,asp的页面传送的文件

2024-05-04 11:06:22
字体:
来源:转载
供稿:网友
 

aspx接受aspx页面的文件很简单,用htmlinputfile,就可以了,但是如果接受html页面post的文件
就不怎么好办了,我仿照asp的方法做法如下,自己测试通过,拿出来给大家共享,可以限制
文件内容,类型,大小,自定义存储位置,在congfig.xml内
html页的内容:(来自fckeditor)
<html>
 <head>
  <title>fckeditor - uploaders tests</title>
  <script language="javascript">

function sendfile()
{
 var suploaderurl = cmbuploaderurl.value ;
 
 if ( suploaderurl.length == 0 )
  suploaderurl = txtcustomurl.value ;
 
 if ( suploaderurl.length == 0 )
 {
  alert( 'please provide your custom url or select a default one' ) ;
  return ;
 }
 
 eurl.innerhtml = suploaderurl ;
 txturl.value = '' ;
 
 frmupload.action = suploaderurl ;
 frmupload.submit() ;
}

function onuploadcompleted( errornumber, fileurl, filename, custommsg )
{
 switch ( errornumber )
 {
  case 0 : // no errors
   txturl.value = fileurl ;
   alert( 'file uploaded with no errors' ) ;
   break ;
  case 1 : // custom error
   alert( custommsg ) ;
   break ;
  case 10 : // custom warning
   txturl.value = fileurl ;
   alert( custommsg ) ;
   break ;
  case 201 :
   txturl.value = fileurl ;
   alert( 'a file with the same name is already available. the uploaded file has been renamed to "' + filename + '"' ) ;
   break ;
  case 202 :
   alert( 'invalid file' ) ;
   break ;
  case 203 :
   alert( "security error. you probably don't have enough permissions to upload. please check your server." ) ;
   break ;
  default :
   alert( 'error on file upload. error number: ' + errornumber ) ;
   break ;
 }
}

  </script>
 </head>
 <body>
  <table cellspacing="0" cellpadding="0" width="100%" border="0" height="100%">
   <tr>
    <td>
     <table cellspacing="0" cellpadding="0" width="100%" border="0">
      <tr>
       <td nowrap >
        select the "file uploader" to use:<br>
        <select id="cmbuploaderurl" name="select1">
         <option selected value="asp/upload.asp">asp</option>
         <option value="php/upload.php">php</option>
         <option value="upload.aspx?type=image">aspx</option>
        </select>
       </td>
       <td nowrap >&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td>
       <td width="100%" >
        custom uploader url:<br>
        <input id="txtcustomurl" disabled type="text">
       </td>
      </tr>
     </table>
     <br>
     <table cellspacing="0" cellpadding="0" width="100%" border="0">
      <tr>
       <td nowrap>
        <form id="frmupload" target="uploadwindow" enctype="multipart/form-data" action="" method="post">
         upload a new file:<br>
         <input type="file" name="newfile"><br>
         <input type="button" value="send it to the server" >
        </form>
       </td>
       <td >&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td>
       <td valign="top" width="100%">
        uploaded file url:<br>
        <input id="txturl" readonly type="text">
       </td>
      </tr>
     </table>
     <br>
     post url: <span id="eurl">&nbsp;</span>
    </td>
   </tr>
   <tr>
    <td height="100%">
     <iframe name="uploadwindow" width="100%" height="100%"></iframe>
    </td>
   </tr>
  </table>
 </body>
</html>
upload.aspx的内容:
<%@ page language="c#" autoeventwireup="true"  codefile="upload.aspx.cs" inherits="upload"%>
下面是后台代码:
using system;
using system.data;
using system.configuration;
using system.collections;
using system.io;
using system.text;
using system.web;
using system.web.security;
using system.web.ui;
using system.web.ui.webcontrols;
using system.web.ui.webcontrols.webparts;
using system.web.ui.htmlcontrols;
using system.xml;
using system.collections.specialized;
public partial class upload : system.web.ui.page
{
 public void sendresults(int errornumber, string fileurl, string filename, string custommsg)
 {
  stringbuilder text = new stringbuilder();
  text.append("<script type=/"text/javascript/">");
  text.append("window.parent.onuploadcompleted(" + errornumber + ",/"" + fileurl.replace("/"", "///"") + "/",/"" + filename.replace("/"", "///"") + "/",/"" + custommsg.replace("/"", "///"") + "/") ;/n");
  text.append(" </script>");
  response.write(text.tostring());
  response.end();
 }
 public void getconfig(string type, out string[] allowedext, out string[] denyedext,out string savepath,out long maxsize)
 {
   xmldocument doc = new xmldocument();
   doc.load(server.mappath(@"./config.xml"));
   xmlelement root=doc.documentelement;
   xmlnodelist imagenodelist=root.getelementsbytagname(type);
   allowedext = imagenodelist[0].firstchild.innertext.trim().split('|');
   denyedext = imagenodelist[0].lastchild.innertext.trim().split('|');
   savepath = root.getelementsbytagname("userpath").item(0).innertext.trim();
   try
   {
    maxsize = convert.toint64(root.getelementsbytagname("maxsize").item(0).innertext.trim());
   }
   catch { maxsize = 10*1024; }
 }
 protected void page_load(object sender, eventargs e)
 {

  string[] allowedext = new string[] { }, denyedext = new string[] { };
  string savepath = string.empty;
  long maxsize = 10000;
  string type = request.querystring["type"];
  if(type!=null&&type!=string.empty)
   type=type.tolower();
  else
   type="file";
  if (type == "image")
  {
   getconfig("image", out allowedext, out denyedext, out savepath,out maxsize);   
  }
  if (type == "file")
  {
   getconfig("file", out allowedext, out denyedext, out savepath, out maxsize);   
  }
  if (type == "flash")
  {
   getconfig("flash", out allowedext, out denyedext, out savepath, out maxsize);  
  }
  if (savepath == string.empty||savepath=="")
   savepath = "~/userfiles/";
  if(!savepath.endswith("/"))savepath+="/";
  /*********************************************************************************
  byte[] bytes1 = system.text.encoding.default.getbytes("这是字符串/n/n/n/n");
  byte[] bytes2 = new byte[] { 1, 33, 23, 3, 0, 56, 55, 235, 5 };//二进制数

  byte[] bytes = new byte[bytes1.length + bytes2.length];

  //合并二进制流
  memorystream ms = new memorystream(bytes);
  ms.write(bytes1, 0, bytes1.length);
  ms.write(bytes2, 0, bytes2.length);

  int count = 0, pos = 0;
  //开始找四个'/n'
  for (int i = 0; i < bytes.length; i++)
  {
   if (bytes[i] == (int)'/n')
   {
    count++;
    if (count == 4)
    {
     pos -= 4;
     break;
    }
   }
  }

  if (count == 4)
  {
   //这里,bytes字节数组里从0 到 pos 的位置就是你要的字符串
   //从pos + 5 开始到最后,就是你要的二进制
  }
  **********************************************************************************/
  byte[] filedata, formdata;

  formdata = request.binaryread(request.contentlength);
  string head = string.empty;
  encoding encoding = encoding.utf8;

  long pos = 0;
  for (long i = 0; i < formdata.longlength; i++)
  {
   if (formdata[i] == (byte)'/r' && formdata[i + 1] == (byte)'/n' && formdata[i + 2] == (byte)'/r' && formdata[i + 3] == (byte)'/n')
   {
    pos = i;
    break;
   }
  }
  if (pos == 0) { response.end(); return; }
  head = encoding.getstring(formdata, 0, (int)pos);
  filedata = new byte[formdata.longlength - pos - 3];
  array.copy(formdata, pos + 4, filedata, 0, formdata.longlength - pos - 4);
  /************************************************************************************************
  //传来的表单形式是:
  //"-----------------------------7d5fa3820f84/r/ncontent-disposition: form-data; name=/"newfile/"; filename=/"f://documents//4(10995).jpg/"/r/ncontent-type: image/pjpeg/r/n/r/n
  //后面是文件数据
   ************************************************************************************************/
  head = head.tolower();
  head = head.remove(0, head.indexof("/r/n") + 2);
  head = head.replace("/"", "");
  string postfilename = string.empty;
  string filename;//no path
  string filetype, fileext;
  postfilename = head.substring(0, head.indexof("/r/n"));//content-disposition: form-data; name=/"newfile/"; filename=/"f://documents//4(10995).jpg/"
  filetype = head.remove(0, postfilename.length + 3);//returns:content-type: image/pjpeg
  postfilename = postfilename.substring(postfilename.indexof("filename=") + "filename=".length);//c:/path/name
  filename = path.getfilename(postfilename);
  fileext = filename.substring(filename.lastindexof(".") + 1);
  if (filedata.longlength > maxsize) {
   sendresults(2, resolveurl(savepath + filename), filename, "too large");
   return;
  }
  bool isallow=false;
  foreach(string ext in denyedext){
   if (ext == fileext) {
    isallow = false;
    sendresults(202, resolveurl(savepath + filename), filename, "forrbiden");
    return;
   }
  }

  foreach (string ext in allowedext) {
   if (ext == fileext) { isallow = true; break; }
  }
  if ( isallow)
  {
   string tmppath = server.mappath(savepath);
   if (!directory.exists(tmppath)) {
    try
    {
     directory.createdirectory(tmppath);
    }
    catch { sendresults(200, resolveurl(savepath + filename), filename, "没有写入权限"); }
   }
   //response.binarywrite(filedata);
   filestream savefilestream= new filestream(tmppath+filename, filemode.openorcreate, fileaccess.readwrite);
   for (long i = 0; i < filedata.longlength; i++)
   {
    savefilestream.writebyte(filedata[i]);
   }
   savefilestream.close();
   sendresults(0, resolveurl(savepath + filename), filename, "no errors");

  }

 }
}


config.xml
<?xml version="1.0" encoding="utf-8"?>
<upload>
    <enabled>true</enabled>
    <userpath></userpath>
 <maxsize>500000</maxsize><!--unit is byte-->
    <file>
        <allow>zip|rar</allow>
        <deny>php|php3|php5|phtml|asp|aspx|ascx|jsp|cfm|cfc|pl|bat|exe|dll|reg|cgi</deny>
    </file>
    <image>
        <allow>jpg|gif|jpeg|png|bmp</allow>
        <deny></deny>
    </image>
    <flash>
        <allow>swf|fla</allow>
        <deny></deny>
    </flash>
</upload>

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表