···········由於案例是使用MVC做的,就直接貼與之相關的代碼,原理都是一樣的,無論是aspx、ashx或者webservice。
HTML:
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<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,
/**
*必須false才會自動加上正確的Content-Type
*/
contentType: false,
/**
* 必須false才會避開jQuery對 formdata 的預設處理
* XMLHttpRequest會對 formdata 進行正確的處理
*/
processData: false,
success: function (data) {
if (data == "true") {
alert("上傳成功。");
}
else {
alert("上傳失敗。");
}
}
});
});
});
</script>
</head>
<body>
<div id="all">
<input type="file" id="myfile" />
<input type="button" id="btnUpload" value="上傳" />
</div>
</body>
</html>
控制器:
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);//儲存檔案
//儲存檔案名稱到資料庫(MVC模式下的資訊添加-後面取圖片顯示時用到)
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);//儲存檔案
//儲存檔案名稱到資料庫(MVC模式下的資訊添加-後面取圖片顯示時用到)
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);
}
}
}