1. 程式人生 > >圖片簡單上傳

圖片簡單上傳

在chhtml頁中新增標籤

<form method="post" enctype="multipart/form-data" id="formData">
<input type="hidden" name="FileName" value="" />
<span>上傳圖片</span>
<input type="file" id="fileUpload" name="file" /><span>上傳圖片input 後給id必須給個name="file"</span>
<img src="" id="showImage" />
</form>

<script type="text/javascript">
$(function () {
$("#fileUpload").change(function () {


//單檔案長傳所以預設取第一個
var formData = new FormData($("#formData")[0]);
$.ajax({
url: '/Product/UploadFile',
type: 'post',
//資料型別不處理
contentType: false,
//資料不處理
processData: false,
//不快取
cache: false,
data:formData,
success: function (data) {
alert(data)
$("input[name=FileName]").val(data);
$("#showImage").attr("src", data);
}
});
});
})
</script>

 

後臺程式碼

public string UploadFile()
{
HttpPostedFileBase httpfile = Request.Files[0];
if (httpfile != null)
{
//獲取路徑
string strPath = Server.MapPath("~/images/");
//判斷是否存在
if (!Directory.Exists(strPath))
Directory.CreateDirectory(strPath);
//獲取所有路徑
string newPath = Path.Combine(strPath, httpfile.FileName);
httpfile.SaveAs(newPath);
return "/images/" + httpfile.FileName;
}
else
return null;

}