··········· Because the case is done using MVC, the code directly attached to it is the same principle, whether it's aspx, ashx, or WebService.
Html:
@{
Layout = null;
}
<! DOCTYPE html>
<meta name= "viewport" content= "Width=device-width"/>
<title>Index</title>
<style>
* {
margin:0px;
padding:0px;
}
#all {
border:1px solid red;
width:800px;
height:100px;
margin:0px Auto;
margin-top:100px;
Text-align:center;
line-height:100px;
}
</style>
<script src= "~/scripts/jquery-1.8.2.js" ></script>
<script>
$ (function () {
$ ("#btnUpload"). Click (function () {
var formData = new FormData ();
Formdata.append ("MyFile", document.getElementById ("MyFile"). Files[0]);
$.ajax ({
URL: "/home/update",
Type: "POST",
Data:formdata,
/**
* Must be false to automatically add the correct Content-type
*/
Contenttype:false,
/**
* Must be false to avoid jquery's default handling of Formdata
* XMLHttpRequest will handle the formdata correctly.
*/
Processdata:false,
Success:function (data) {
if (data = = "true") {
Alert ("Upload succeeded.") ");
}
else {
Alert ("Upload failed.") ");
}
}
});
});
});
</script>
<body>
<div id= "All" >
<input type= "File" id= "MyFile"/>
<input type= "button" id= "Btnupload" value= "Upload"/>
</div>
</body>
Controller:
Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Web;
Using SYSTEM.WEB.MVC;
Using Wode. Models;
Namespace Wode. Controllers
{
public class Homecontroller:controller
{
//
Get:/home/
Public ActionResult Index ()
{
return View ();
}
Private Ceshientities db = new ceshientities ();
Public ActionResult Update ()
{
Response.ContentType = "Text/plain";
if (Request.Files.Count > 0)
{
var myFile = request.files["MyFile"];
Myfile.saveas (Server.MapPath ("~/upload/") + myfile.filename)//Save File
Save file name to database (add to information in MVC mode-use when the picture is displayed later)
TC T = new TC ();
t.tc_img = Myfile.filename;
DB.TC.ADD (t);
if (db. SaveChanges () >0)
{
Return Json ("true");
}
}
Return Json ("false");
}
protected override void Dispose (bool disposing)
{
Db. Dispose ();
Base. Dispose (disposing);
}
}
}
Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Web;
Using SYSTEM.WEB.MVC;
Using Wode. Models;
Namespace Wode. Controllers
{
public class Homecontroller:controller
{
//
Get:/home/
Public ActionResult Index ()
{
return View ();
}
Private Ceshientities db = new ceshientities ();
Public ActionResult Update ()
{
Response.ContentType = "Text/plain";
if (Request.Files.Count > 0)
{
var myFile = request.files["MyFile"];
Myfile.saveas (Server.MapPath ("~/upload/") + myfile.filename)//Save File
Save file name to database (add to information in MVC mode-use when the picture is displayed later)
TC T = new TC ();
t.tc_img = Myfile.filename;
DB.TC.ADD (t);
if (db. SaveChanges () >0)
{
Return Json ("true");
}
}
Return Json ("false");
}
protected override void Dispose (bool disposing)
{
Db. Dispose ();
Base. Dispose (disposing);
}
}
}