ASPX принимает файл страницы ASPX очень прост, просто используйте htmlinputfile, все в порядке, но если вы принимаете файл Post Page HTML.
Это не очень легко справиться.
Содержание файла, тип, размер, пользовательское положение хранения, в conmfig.xml
Содержание HTML -страницы: (от fckeditor)
<html>
<голова>
<Title> fckeditor -Uploaders Tests </title>
<script language = "javascript">
Функция sendfile ()
{{
var suploaderurl = cmbuploaderurl.value;
If (suploaderurl.length == 0)
suploaderurl = txtcustomall.value;
If (suploaderurl.length == 0)
{{
Alert («Пожалуйста, предоставьте свой пользовательский URL или выберите по умолчанию один»);
Возвращаться;
}
eurl.innerhtml = suploaderurl;
txturl.value = '';
frmupload.action = suploaderurl;
frmupload.submit ();
}
Function OnuploadCompleted (Errornumber, FileUrl, Filename, Custmssg)
{{
Switch (Errornumber)
{{
Случай 0: // Нет ошибок
txturl.value = fileUrl;
Alert ('файл загружен без ошибок');
Перерыв;
Случай 1: // Пользовательская ошибка
Оповещение (custmssg);
Перерыв;
Случай 10: // Пользовательское предупреждение
txturl.value = fileUrl;
Оповещение (custmssg);
Перерыв;
Случай 201:
txturl.value = fileUrl;
Alert ('файл с тем же именем доступен Almedy. Файл загрузки переименован в « + filename +' '');
Перерыв;
Случай 202:
Alert ('неверный файл');
Перерыв;
Случай 203:
ALERT («Ошибка безопасности. Вы, вероятно, не не в том, что нет никаких разрешений для загрузки. Пожалуйста, проверьте свой сервер».);
Перерыв;
ПО УМОЛЧАНИЮ:
alert ('ошибка при загрузке файла. Eric number:' + errornumber);
Перерыв;
}
}
</script>
</head>
<тело>
<Таблица cell -spacing = "0" cellpadding = "0">
<tr>
<Td>
<Таблица cell -spacing = "0" cellpadding = "0">
<tr>
<Td Now4>
Выберите «Загрузчик файла» для использования: <br>
<select id = "cmbuploaderurl" name = "select1">
<опция выберите значение = "asp/upload.asp"> asp </option>
<option value = "php/upload.php"> php </option>
<option value = "upload.aspx? type = image"> aspx </option>
</select>
</td>
<TD 44 & NBSP;
<Td>
Пользовательский URL загрузчика: <br>
<input id = "txtcustomall" disabled type = "text">
</td>
</tr>
</table>
<br>
<Таблица cell -spacing = "0" cellpadding = "0">
<tr>
<Td Now4>
<Form id = "frmupload" target = "uploadwindow" ectype = "multipart/form-data" action = "" method = "post">
Загрузите новый файл: <br>
<input type = "file" name = "newfile"> <br>
<input type = "button" value = "Отправить его на сервер">
</form>
</td>
<td> & nbsp;
<td value = "top">
Загруженный URL -адрес файла: <br>
<input id = "txturl" readonly type = "text">
</td>
</tr>
</table>
<br>
Post url: <span id = "eurl"> & nbsp;
</td>
</tr>
<tr>
<Td>
<ifme name = "uploadwindow"> </iframe>
</td>
</tr>
</table>
</body>
</html>
Содержание opload.aspx:
<%@ page language = "c#" autoeventwireup = "true" codefile = "upload.aspx.cs" enherits = "upload"%>%>
Ниже приведено фоновый код:
Использование системы;
Использование System.data;
Использование System.configuration;
Использование System.collections;
Использование System.io;
Использование System.Text;
Использование System.Web;
Использование System.Web.Security;
Использование System.Web.UI;
Использование System.Web.UI.WebControls;
Использование System.web.ui.webcontrols.webparts;
Использование System.web.ui.htmlControls;
Использование System.xml;
Использование System.collections.specialized;
Общественная частичная загрузка класса: 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 (" + errorrnumber + ",/" + fileurl.replace ("/", "//" "),/" + filename.replace ("/" "," // /"") + "/",/" + Custommsg.replace ("/"", "//" "));/n");/n ");/n");/n ");///// n ");/n");/n ");/n");/n ");
text.append ("</script>");
response.write (text.toString ());
response.end ();
}
Public void getfig (тип строки, out string [] allowedext, out string [] denyedext, out long maxsize), out long maxsize)
{{
xmldocumet doc = new xmldocument ();
doc.load (server.mappath (@"./ config.xml");
xmlement root = doc.documentelement;
Xmlnodelist imageexodelist = root.getElementsbytagname (type);
Allowedext = ImageNodelist [0] .firstchild.innertext.trim ().
Denyedext = ImageNodelist [0] .lastchild.innertext.trim ().
savePath = root.getElementsbybytagname ("userPath").
пытаться
{{
maxsize = convert.toint64 (root.getelementsbytagname ("maxsize"). item (0) .innertext.trim ());););););););) reext.trim ());););););); ;););););););) Reext.trim ();););););););
}
Catch {maxSize = 10*1024;}
}
Защищенная void page_load (отправитель объекта, Eventargs E)
{{
string [] allowedExt = new String [] {}, denyedext = new String [] {};
string savePath = string.empty;
длинный maxsize = 10000;
string type = request.querystring ["type"];
if (type! = null && type! = String.empty)
Type = type.tolower ();
еще
type = "file";
if (type == "изображение")
{{
GetConfig («Изображение», Out outedExt, Out denyedext, Out SavePath, Out MaxSize);
}
if (type == "файл")
{{
getConfig ("file", out out ullextext, out deenyedext, out savepath, out maxsize);
}
if (type == "flash"))
{{
getConfig («Flash», Out outedextext, Out denyedext, Out SavePath, Out MaxSize);
}
ifpath == string.empty || savepath == "")
savePath = "~/userFiles/";
if (! SavePath.endswith ("/") savePath+= "/";
/********************************************* ** *************************************
byte [] bytes1 = system.text.encoding.default.getbytes ("Это строка/n/n/n/n");
Byte [] Bytes2 = новый байт [] {1, 33, 23, 3, 0, 56, 55, 235, 5};
byte [] bytes = new Byte [bytes1.length + bytes2.length];
// слияние двоичного потока
MemoryStream MS = New MemoryStream (байты);
Ms.Write (Bytes1, 0, Bytes1.length);
Ms.Write (Bytes2, 0, Bytes2.length);
int count = 0, pos = 0;
// начать найти четыре '/n'
для (int i = 0; i <bytes.length; i ++)
{{
if (bytes [i] == (int) '/n')
{{
Count ++;
if (count == 4)
{{
Pos- = 4;
Перерыв;
}
}
}
if (count == 4)
{{
// Здесь позиция от 0 до POS в байтовом массиве - это нужная строка
// С самого начала POS + 5 до конца, бинарный, который вы хотите
}
********************************************** **********************************************
Byte [] filedata, formdata;
FormData = request.binaryRead (request.contentlength);
string head = string.empty;
кодирование кодирования = кодирование.utf8;
длинный POS = 0;
для (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;
Перерыв;
}
}
if (pos == 0) {response.end ();
Head = Encoding.getString (formData, 0, (int) pos);
FileData = новый байт [formData.LongLength -pos -3];
Array.copy (formdata, pos + 4, filedata, 0, formdata.longlength -pos -4);
/********************************************* ** ********************************************* ***
// приходит форма формы:
// "--------------------------------- 7d5fa3820f84/r/ncontent-disposition: form-data; name =/" newfile/ ".
// позже данные файла
********************************************** ********************************************* ***********
Head = Head.Tolower ();
Head = Head.remove (0, Head.indexof ("/r/n");
Head = Head.Replace ("/" "," ");
string postfilename = string.empty;
Строка файла; // Нет пути
String fileType, fileExt;
PostFilename = Head.SubString (0, Head.Indexof ("/r/n"); // Содержимое Disposition: Form-Data; name =/"newfile/"; 4 (10995) .jpg/"
FileType = Head.remove (0, PostFilename.length + 3);
Postfilename = postfilename.substring (postfilename.indexof ("filename =") + "filename =". Length);
filename = path.getFilename (postfilename);
filext = filename.substring (filename.lastindexof (".") + 1;
ifdata.longlength> maxsize {{
SendResults (2, ResolveUrl (SavePath + FileName), имя файла, «слишком большой»);
Возвращаться;
}
Bool Isallow = false;
Foreach (string ext in denyedext) {
if (ext == fileext) {
Isallow = false;
SendResults (202, ResolveUrl (SavePath + FileName), имя файла, «запрещено»);
Возвращаться;
}
}
Foreach (string ext in Allext) {{
if (ext == fileext) {isallow = true;
}
if (isallow)
{{
String tmppath = server.mappath (savePath);
if (! Directory.exists (tmppath)) {{{
пытаться
{{
Directory.createdirectory (tmppath);
}
Catch {SendResults (200, ResolveUrl (SavePath + FileName), имя файла, «Нет разрешений на запись»);}
}
//Response.binaryWrite (FileData);
FileStream SaveFileStream = new FileStream (tmppath+имя файла, filemode.openorcreate, fileCcess.readWrite);
для (длинный i = 0; i <fledata.longlength; i ++)
{{
SaveFileStream.WriteByte (FileData [i]);
}
SaveFileStream.Close ();
SendResults (0, ResolveUrl (SavePath + FileName), FilenAMame, «Без ошибок»);
}
}
}
config.xml
<?
<pload>
<edabled> true </enabled>
<userPath> </userPath>
<MaxSize> 500000 </maxSize> <!-Блок-это byte->
<File>
<Allow> Zip |
<Deny> Php |
</file>
<Image>
<Allow> JPG |
<Deny> </deny>
</image>
<Flash>
<Allow> SWF |
<Deny> </deny>
</flash>
</upload>