MVC - 上傳圖片到指定路徑(Server)

  • 1230
  • 0

提供使用者將圖檔上傳到Server的指定路徑底下

在MVC的架構底下,將圖檔上傳並存到Server的指定路徑底下

前端畫面:

HTML

@Html.LabelFor(model => model.PictureID, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-6">
        
        <img id="preview_progressbarTW_img" src="@TempData["ImageSrc"]" height="320" width="180" style="display:block"/>
        <input type="file" accept="image/gif, image/jpeg, image/png" class="form-control-file" id="PictureUpload" style="width: 250px;padding-top:7px;display:inline-block">
        <button class="btn btn-default" id="btnPictureUpload" type="button" style="display:inline-block">圖片上傳</button>
        @Html.HiddenFor(Model => Model.PictureID, new { @id = "hidPictureID" })
    </div>

@TempData["ImageSrc"] 是如果之前有上傳過,可以將路徑寫到TempData["ImageSrc"] ,圖片就可以預覽

JS:

<script type="text/javascript">
var _UploadObject = new FormData();

$(function () {

	//上傳圖片 - 選擇檔案
	$('#PictureUpload').on('change', function (e) {
		//取得檔案
		var files = e.target.files;

		if (files.length > 0) {
			if (window.FormData !== undefined) {
				var FileSize = files[0].size / 1048576; //size in mb
				if (FileSize > 20) {
					alert('檔案大小不得超過20M,請重新選擇檔案!');
					$('#PictureUpload').val('');
					return false;
				}
				var FileExtension = Commonutility.GetFileExtension(files[0].name);
				if (FileExtension == 'jpg' || FileExtension == 'png' ) {
					//因為IE11 不支援Formdata.get,所以先判斷是否undefined
					if (_UploadObject.get != undefined) {
						if (_UploadObject.get("UploadFile") == null) {
							_UploadObject.append("UploadFile", files[0]);
						}
						else {
							_UploadObject.delete('UploadFile');
							_UploadObject.append("UploadFile", files[0]);
						}
					}
					else {
						//IE 也不支援delete,所以直接append就好,檔案會後蓋前
						_UploadObject.append("UploadFile", files[0]);
						UploadFileName.FileOne = files[0].name;
					}   
					readURL(this);
					alert('圖片預覽完成後,請記得點擊圖片上傳,以完成宣導圖片設定。');
				}
				else {
					alert('請上傳正確圖片檔檔案');
					$('#PictureUpload').val('');
					return false;
				}
			}
			else {
				alert("此瀏覽器不支援HTML5檔案上傳");
			}
		}
	});

	//實際將圖片上傳
	$('#btnPictureUpload').on('click', function () {
		if (window.FormData !== undefined) {
			//IE 只要選過資料以後,按取消鍵也不會檔案消失
			if ($.trim($('#PictureUpload').val()).length === 0) {
				alert('請先選擇資料再點選上傳!');
				return false;
			}
			$.ajax({
				type: "POST",
				url: '@Url.Action("PictureUpload")',
				async: false,
				contentType: false,
				processData: false,
				data: _UploadObject,
				success: function (_result) {
					if (_result.Success == true) {
						$('#hidPictureID').val(_result.Message);
						alert('圖片上傳成功!');
					}
					else {
						alert(_result.Message);
					}
				},
				error: function (error) {
					alert('error; ' + error);
				}
			});
		} else {
			alert("此瀏覽器不支援HTML5檔案上傳");
		}
	});

	$('#btnSubmit').on('click', function () {
		if ($.trim($('#PictureUpload').val()).length === 0) {
			alert('請點擊圖片上傳,以完成宣導圖片設定!');
			return false;
		}

		if ($.trim($('#hidPictureID').val()).length === 0) {
			alert('請確認圖片上傳完成,以完成宣導訊息設定!');
			return false;
		}
		$('#submitForm').submit();
	});
});

//讓上傳的圖片可以預覽
function readURL(input) {
	if (input.files && input.files[0]) {
		var reader = new FileReader();
		reader.onload = function (e) {
			$("#preview_progressbarTW_img").attr('src', e.target.result);
		}
		reader.readAsDataURL(input.files[0]);
	}
}

</script>

後端的CS

[HttpPost]
public ActionResult PictureUpload()
{
	ResponseResult _resultObject = new ResponseResult();
	GuidanceService guidanceService = new GuidanceService();

	// 取得目前 HTTP 要求的 HttpRequestBase 物件
	foreach (string file in Request.Files)
	{
		var fileContent = Request.Files[file];
		if (fileContent != null && fileContent.ContentLength > 0)
		{
			// 取得的檔案是stream
			var stream = fileContent.InputStream;
			String fileName = fileContent.FileName;
			// 檢查檔名是否存在
			fileName = guidanceService.CheckUploadFileName(fileName);

			String MimeType = fileContent.ContentType;

			#region Copy 檔案到指定路徑底下
			var path = Path.Combine(Server.MapPath("~/FileUploads/"), fileName);
			using (var fileStream = System.IO.File.Create(path))
			{
				stream.CopyTo(fileStream);
			}
			//如果有COPY檔案的話要歸零
			stream.Position = 0;
			#endregion

			_resultObject = guidanceService.InsertGuidancePicture(PictureFileName: fileName);
		}
	}

	return Json(_resultObject);
}