圖片上傳
<div class="form-group">
<label for="image">上傳圖片</label><br />
<input id="file" class="filepath" οnchange="changepic(this)" type="file" name="image" /><br /><br />
<img src="" id="show" width="200">
</div>
圖片預覽
<script>
function changepic() {
var reads = new FileReader();
f = document.getElementById('file').files[0];
reads.readAsDataURL(f);
reads.onload = function (e) {
document.getElementById('show').src = this.result;
};
}
</script>
ajax 圖片傳遞到後端
<script type="text/javascript">
$(document).ready(function () {
$("form").submit(function () {
var fileObj = $('#file')[0].files[0];
var formFile = new FormData();
//加入文件對象,想接口傳入參數file,id
formFile.append("image", fileObj);
var data = formFile;
$.ajax({
url: '/Article/PublishArticle',
type: 'post',
dataType: 'json',
cache: false,//上傳文件無需緩存
processData: false,//用於對data參數進行序列化處理 這裏必須false
//必須
contentType: false,
data: data,
success: function (data) {
//對返回數據進行處理
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
});
</script>
}
控制器接收圖片文件並保存(Uppictures項目裏存取圖片的文件夾路徑)
string imagePath = Request.MapPath("~/Uppictures/" + Request.Files["image"].FileName);
Request.Files["image"].SaveAs(imagePath);