In addition, no unified upload function is set up. The code is transformed. I want to use ajax to upload images asynchronously. This technology should be quite old. As a result, the powerful cnblogs can easily find this article, which is based on the gourd painting, and the author's Labor achievements can be taken directly ". Soon the code was fully transformed. But when I publish the program to the server, the problem arises. The uploaded file is invalid! Khan ~ It is the consequence of laziness. Continue to open the previous reference article. The author explained that it can only be used locally and cannot be published to the server. I thought, do I still have to use the iframe + http post depressing method ??
As a result, I opened a more powerful google and began to search for solutions globally. Finally, I was quite frustrated. Find "jquery. form. js ".
To upload an image asynchronously, follow these steps:
1. Reference The jquery js framework (there is no need to talk about the benefits of this stuff) and then reference "jquery. form. js ".
2. Set up the general processing program ashx.
The core code is as follows:
Html:
Copy codeThe Code is as follows:
<Asp: Content ID = "Content3" ContentPlaceHolderID = "Head" runat = "server">
<Script src = "<% = Url. Content ("~ /Scripts/jquery-1.4.1.js ") %>" type = "text/javascript"> </script>
<Script src = "<% = Url. Content ("~ /Scripts/jquery. form. js ") %>" type = "text/javascript"> </script>
<Script type = "text/javascript">
$ (Function (){
// Upload an image
$ ("# BtnUpload"). click (function (){
If ($ ("# flUpload"). val () = ""){
Alert ("select an image file and Click Upload. ");
Return;
}
$ ('# UpLoadForm'). ajaxSubmit ({
Success: function (html, status ){
Var result = html. replace ("<pre> ","");
Result = result. replace ("</pre> ","");
$ ("# Image"). attr ('src', result );
Alert (result );
}
});
});
});
Ashx is as follows:
Copy codeThe Code is as follows:
Namespace TestMvc. Utility
{
/// <Summary>
/// Summary description for PicUploadHander
/// </Summary>
Public class PicUploadHander: IHttpHandler
{
Public void ProcessRequest (HttpContext context)
{
Context. Response. ContentType = "text/plain ";
// Verify the upload permission TODO
String _ fileNamePath = "";
Try
{
_ FileNamePath = context. Request. Files [0]. FileName;
// Start upload
String _ savedFileResult = UpLoadImage (_ fileNamePath, context );
Context. Response. Write (_ savedFileResult );
}
Catch
{
Context. Response. Write ("Upload submission error ");
}
}
Note: ajax asynchronous data is used for the entire upload, and jquery calls back the relative path of the image on the server after the upload is successful. In general, this method is stronger than the traditional Image Upload method.
This sample code is downloaded here and tested in FireFox. Http://xiazai.jb51.net/201011/yuanma/AjaxUploadPic.rar