Asp. NET in the WebForm development mode, encapsulates the FileUpload control, can be convenient for file upload operation. But sometimes, you may not want to use the server controls in ASP.net, just use the input tag to implement file uploads. Of course, it is also possible. The following is a summary of how uploaded files are used in your project.
In this paper, we summarize the methods of uploading files in three kinds of asp.net.
first, the use of asp.net fileupload server-side control to implement upload
It is convenient to upload files using server-side controls in ASP.net fileupload. FileUpload the upload operation is encapsulated, you only need to call the SaveAs method to complete the upload. Here is the simple upload code.
<p> server-side control upload </p>
<asp:fileupload id= "Myfileupload" runat= "Server"/>
<asp:button id= "Fileuploadbutton" runat= "server" text= "upload"
onclick= "Fileuploadbutton_click"/>
protected void Fileuploadbutton_click (object sender, EventArgs e)
{
if (myfileupload.hasfile)
{
String filePath = Server.MapPath ("~/uploadfiles/");
string fileName = MyFileUpload.PostedFile.FileName;
Myfileupload.saveas (FilePath + fileName);
Response.Write ("<p > Upload Success!</p>");
}
Else
{
Response.Write ("<p > Please select file to upload!</p>");
}
}
Of course, in the actual project can not be so simple to save the file. You should at least add some file-type judgments to prevent users from uploading files that can threaten system security. You can use the client JS authentication method, can also be in the. CS server-side code to verify.
Under the ASP.net webform development framework, we can also use HTML input tags to upload files. At this point, it should be noted that this type file input tag needs to add runat= "Server" attribute, otherwise in the background request.files not get uploaded files.
<p> use HTML input tags to upload </p>
<input type= "File" Name= "Myfileuploadinput" runat= "Server"/><asp:button
Id= "Inputfileuploadbutton" runat= "server" text= "upload"
onclick= "Inputfileuploadbutton_click"/>
protected void Inputfileuploadbutton_click (object sender, EventArgs e)
{
httpfilecollection files = request.files;
String filePath = Server.MapPath ("~/uploadfiles/");
if (Files. Count!= 0)
{
String fileName = Files[0]. FileName;
Files[0]. SaveAs (Path.Combine (FilePath, fileName));
Response.Write ("<p> upload success </p>");
}
Else
{
Response.Write ("<p> not get to files:" + files. Count.tostring () + "</p>");
}
}
In this way to upload, the advantage is that you can easily use JS to generate multiple input tags to upload multiple files. It is important to note at this point that the input label must have a name attribute. In the background, you only need to loop through the SaveAs () method.
The next two ways of uploading (two and three) will use Ajax to submit data asynchronously, in the background using a. ashx file for processing. Two ways to share a file, Ajax in the URL parameter plus a method to distinguish which way to pass. The background code is as follows:
public void ProcessRequest (HttpContext context)
{
String method = Context. Request.querystring["Method"]. ToString ();
Switch (method)
{
Case "Ajaxfileupload":
Ajaxfileupload (context);
Break
Case "Formdataupload":
Formdataupload (context);
Break
Default
Break
}
}
private static void Formdataupload (HttpContext context)
{
httpfilecollection files = context. Request.Files;
String msg = string. Empty;
String error = String. Empty;
if (Files. Count > 0)
{
Files[0]. SaveAs (configurationmanager.appsettings["FilePath"). ToString () + System.IO.Path.GetFileName (Files[0]. FileName));
msg = "Success!" The file size is: "+ files[0]." ContentLength;
string res = "{error: '" + Error + "', msg: ' + msg +" '} ";
Context. Response.Write (RES);
Context. Response.End ();
}
}
private static void Ajaxfileupload (HttpContext context)
{
httpfilecollection files = context. Request.Files;
String msg = string. Empty;
String error = String. Empty;
if (Files. Count > 0)
{
Files[0]. SaveAs (configurationmanager.appsettings["FilePath"). ToString () + System.IO.Path.GetFileName (Files[0]. FileName));
msg = "Success!" The file size is: "+ files[0]." ContentLength;
string res = "{error: '" + Error + "', msg: ' + msg +" '} ";
Context. Response.Write (RES);
Context. Response.End ();
}
}
second, using the input tag in HTML to add Formdata object to achieve
Using this method to upload attachments, there are some requirements for browsers. Formdata belongs to the new features of HTML5, IE browser only support in 10 or more. Therefore, the pros and cons of their own trade-offs, but it is convenient to use. The following direct code:
function Formdataupload () {
var fileupload = document.getElementById (' filetoupload '). files;
var formdata = new Formdata ();
Formdata.append (' Files ', fileupload[0]);
var xmlHttp = new XMLHttpRequest ();
Xmlhttp.open ("Post", ' handlers/fileupload.ashx?method=formdataupload ');
Xmlhttp.onreadystatechange = function () {
if (xmlhttp.readystate = = 4 && xmlhttp.status = 200) {
Alert (' upload success ');
}
}
Xmlhttp.send (Formdata);
}
Iii. using the Ajaxfileupload.js plugin in jquery to implement the upload
Using this method, you need to refer to Jquery.js and ajaxfileupload.js two files. Another area to note is the version-matching problem for two files, which may appear to be abnormal during use. At this time to play the role of search engines, can always find the solution you need.
The JavaScript code is as follows:
function Ajaxfileupload () {
$.ajaxfileupload (
{
URL: ' Handlers/fileupload.ashx?method=ajaxfileupload ',
Secureuri:false,
Fileelementid: ' Filetoupload ',
DataType: ' JSON ',
Success:function (data, status) {
$ (' #img1 '). attr ("src", data.imgurl);
if (typeof (Data.error)!= ' undefined ') {
if (Data.error!= ') {
alert (data.error);
} else {
alert (data.msg);
}
}
},
Error:function (data, status, E) {
Alert (e);
}
}
)
return false;
}
The code on the HTML page is as follows:
<script type= "Text/javascript" src= "Scripts/jquery-1.4.1.js" ></script>
<script type= "Text/javascript" src= "Scripts/ajaxfileupload.js" ></script>
<script type= "Text/javascript" >
$ (function () {
$ ("#ajaxfileuploadButton"). Click (function () {
Ajaxfileupload ();
})
$ ("#formdataButton"). Click (function () {
Formdataupload ();
})
});
</script>
<title></title>
<script type= "Text/javascript" >
</script>
<body>
<input type= "File" id= "Filetoupload" name= "Filetoupload"/>
<input type= "button" id= "Ajaxfileuploadbutton" value= "ajaxfileupload plugin upload"/>
<input type= "button" id= "Formdatabutton" value= "Formdata way to upload"/>
</body>
Summary
The above summed up several ways to upload files, but also a simple description of some of the use of the need to pay attention to the problem. Of course, there are more problems that may be encountered, and if you encounter other bizarre problems during the development process, you can search for related problems yourself. Each of the problems encountered in the resolution, is a more in-depth understanding of this knowledge. Progress slowly in solving problems.