Asp. net 2.0 display thumbnail without refreshing picture upload concrete implementation
- 2020-06-07 04:24:56
- OfStack
Compatibility is not bad: FF, CH, IE, cheetah, can be achieved. If you see echo. Success, of course.
After several days of non-stop drilling, finally this 2 goods out. That was a great effort. But it was a happy moment.
Step 1: We need to load several JS libraries.
jquery library.
jquery. form. js library.
Download both libraries and reference them to the page.
Here is the JS code on the page:
function upload() {
var options = {
type: "POST", // Of course this is the mode of transport
url: '../Include/Files.ashx', //1 The path of the general handler
success: function (msg) { // Parameters returned
$("#server_img").attr("src", msg); // Echo the picture.
}
};
// will options To pass to ajaxForm
$('#aspnetForm').ajaxSubmit(options);
}
Step 2:1 Code in the general handler
public void ProcessRequest(HttpContext context)
{
HttpFileCollection files = context.Request.Files; // From Gets the file object
if (files.Count > 0)
{
string path = ""; // Path string
Random rnd = new Random();
for (int i = 0; i < files.Count; i++)
{
HttpPostedFile file = files[i]; // Get the file object
if (file.ContentLength > 0)
{
string fileName = file.FileName;
string extension = Path.GetExtension(fileName);
int num = rnd.Next(5000, 10000); // The file name
path = "../../UserFiles/temp/" + num.ToString() + extension;
file.SaveAs(System.Web.HttpContext.Current.Server.MapPath(path)); // Save the file.
}
}
context.Response.Write(path); // Returns the path after the file is stored for echo.
}
}
Step 3: The code in html or aspx.
The following two lines of code are inserted anywhere in html or aspx. I think it's possible.
<img id="server_img" width="360px" style="border: 1px solid #ccc; padding: 2px;" title="" alt="" /> // Used to echo images
<asp:FileUpload ID="Up_load" runat="server" onchange="upload()" ontextchange="upload()"/> // Upload images, automatically, two events to ensure that all browsers are compatible.