註釋:將帶有的HTML標籤的字符串,轉換成的HTML標籤輸出
用法:
@{
var message =“<script> alert("測試輸出")</script>”
}
例:
@{
var message =“<script> alert("測試輸出")</script>”
}
<html>
<head>
<title></title>
</head>
<body>
@Html.Raw(@message)
</body>
</html>
@{
var message =“<script> alert("測試輸出")</script>”
}
@{
var message =“<script> alert("測試輸出")</script>”
}
<html>
<head>
<title></title>
</head>
<body>
@Html.Raw(@message)
</body>
</html>
@Html.ActionLink("檔案上傳", "Index", "FileUpload", new { area = "" }, null)
@model WebServiceTest.Models.UploadFileInfo
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
<div>@ViewBag.Message</div>
@using(Html.BeginForm("Index", "FileUpload",
new { ReturnUrl = ViewBag.ReturnUrl },
FormMethod.Post, new { @class = "form-inline", role = "form", enctype = "multipart/form-data" })) {
@Html.AntiForgeryToken()
@Html.ValidationSummary()
<input type="file" name="FileName" id="FileName" multiple="multiple" />
<img id="image1" src="" />
<br /><br />
<input type="submit" name="btnSubmit" id="btnSubmit" value="Submit" />
}
@section scripts{
<script>
$("#FileName").change(function () {
InputLoadImageToBindImageElement(this, $('#image1'));
});
function InputLoadImageToBindImageElement(inputEl, imgEl) {
if (inputEl.files && inputEl.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$(imgEl).attr('src', e.target.result);
}
reader.readAsDataURL(inputEl.files[0]);
}
}
</script>
}
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebServiceTest.Models;
namespace WebServiceTest.ControllersForUser {
public class FileUploadController : Controller {
// GET: FileUpload
public ActionResult Index() {
UploadFileInfo uploadFileInfo = new UploadFileInfo();
return View(uploadFileInfo);
}
[HttpPost]
public ActionResult Index(UploadFileInfo uploadFileInfo) {
foreach(string upload in Request.Files) {
if(!(Request.Files[upload] != null && Request.Files[upload].ContentLength > 0))
continue;
int memUsage_baseline_id = 0;
int timingComp_baseline_id = 0;
if(upload == "FileUploadMemoryUsage" || upload == "FileUploadResultsComparison")
if(upload == "FileUploadMemoryUsage")
if(Request.Params["memUsage_project"] == null || Request.Params["memUsage_project"] == "")
ModelState.AddModelError("Project", "Please Select Project for Memory Usage");
else
memUsage_baseline_id = int.Parse(Request.Params["memUsage_project"]);
else
if(Request.Params["resultsComp_project"] == null || Request.Params["resultsComp_project"] == "")
ModelState.AddModelError("Project", "Please Select Project for Timing Comparison");
else
timingComp_baseline_id = int.Parse(Request.Params["resultsComp_project"]);
HttpPostedFileBase file = Request.Files[upload];
if(ModelState.IsValid)
if(file == null)
ModelState.AddModelError("File", "Please Upload Your file");
else if(file.ContentLength > 0) {
int MaxContentLength = 1024 * 1024 * 3; //3 MB
string[] AllowedFileExtensions = new string[] { ".jpg", ".gif", ".png", ".pdf" };
if(!AllowedFileExtensions.Contains(file.FileName.Substring(file.FileName.LastIndexOf('.'))))
ModelState.AddModelError("File", "Please file of type: " + string.Join(", ", AllowedFileExtensions));
else if(file.ContentLength > MaxContentLength)
ModelState.AddModelError("File", "Your file is too large, maximum allowed size is: " + MaxContentLength + " MB");
else {
if(!Directory.Exists(Server.MapPath("~/Upload")))
Directory.CreateDirectory(Server.MapPath("~/Upload"));
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Upload"), fileName);
file.SaveAs(path);
ModelState.Clear();
//ViewBag.Message = "File uploaded successfully";
TempData["message"] = "File uploaded successfully";
}
}
}
return View();
}
}
}
<script>
function InputLoadImageToBindImageElement(inputEl, imgEl) {
if (inputEl.files && inputEl.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$(imgEl).attr('src', e.target.result);
}
reader.readAsDataURL(inputEl.files[0]);
}
}
</script>
<img src="" id="image1" />
<input type="file" name="name" id="iptImage1" value="" />
<script>
$("#iptImage1").change(function () {
InputLoadImageToBindImageElement(this, $('#image1'));
});
</script>
@model WebServiceTest.Models.UploadFileInfo
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
<div>@ViewBag.Message</div>
@using(Html.BeginForm("Index", "FileUpload",
new { ReturnUrl = ViewBag.ReturnUrl },
FormMethod.Post,
new { @class = "form-inline", role = "form", enctype = "multipart/form-data" })) {
@Html.AntiForgeryToken()
@Html.ValidationSummary()
<input id="FileName" multiple="multiple" name="FileName" type="file" />
<img id="image1" src="" />
<input id="btnSubmit" name="btnSubmit" type="submit" value="Submit" />
}
@section scripts{
<script>
$("#FileName").change(function () {
InputLoadImageToBindImageElement(this, $('#image1'));
});
function InputLoadImageToBindImageElement(inputEl, imgEl) {
if (inputEl.files && inputEl.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$(imgEl).attr('src', e.target.result);
}
reader.readAsDataURL(inputEl.files[0]);
}
}
</script>
}
private static async Task<apiresult> JsonPostAsync(APIData apiData)
{
APIResult fooAPIResult;
using (HttpClientHandler handler = new HttpClientHandler())
{
using (HttpClient client = new HttpClient(handler))
{
try
{
#region 呼叫遠端 Web API
string FooUrl = $"http://localhost:8089/api/Values";
HttpResponseMessage response = null;
#region 設定相關網址內容
var fooFullUrl = $"{FooUrl}";
// Accept 用於宣告客戶端要求服務端回應的文件型態 (底下兩種方法皆可任選其一來使用)
//client.DefaultRequestHeaders.Accept.TryParseAdd("application/json");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Content-Type 用於宣告遞送給對方的文件型態
//client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json");
var fooJSON = JsonConvert.SerializeObject(apiData);
// https://msdn.microsoft.com/zh-tw/library/system.net.http.stringcontent(v=vs.110).aspx
using (var fooContent = new StringContent(fooJSON, Encoding.UTF8, "application/json"))
{
response = await client.PostAsync(fooFullUrl, fooContent);
}
#endregion
#endregion
#region 處理呼叫完成 Web API 之後的回報結果
if (response != null)
{
if (response.IsSuccessStatusCode == true)
{
// 取得呼叫完成 API 後的回報內容
String strResult = await response.Content.ReadAsStringAsync();
fooAPIResult = JsonConvert.DeserializeObject<apiresult>(strResult, new JsonSerializerSettings { MetadataPropertyHandling = MetadataPropertyHandling.Ignore });
}
else
{
fooAPIResult = new APIResult
{
Success = false,
Message = string.Format("Error Code:{0}, Error Message:{1}", response.StatusCode, response.RequestMessage),
Payload = null,
};
}
}
else
{
fooAPIResult = new APIResult
{
Success = false,
Message = "應用程式呼叫 API 發生異常",
Payload = null,
};
}
#endregion
}
catch (Exception ex)
{
fooAPIResult = new APIResult
{
Success = false,
Message = ex.Message,
Payload = ex,
};
}
}
}
return fooAPIResult;
}
[HttpPost]
public APIResult Post([FromBody]APIData value)
{
APIResult foo;
if (value.Id == 777)
{
foo = new APIResult()
{
Success = true,
Message = "透過 post 方法,接收到 Id=777 資料",
Payload = value
};
}
else
{
foo = new APIResult()
{
Success = false,
Message = "無法發現到指定的 ID",
Payload = null
};
}
return foo;
}
static void Main(string[] args)
{
var fooAPIData = new APIData()
{
Id = 777,
Name = "VulcanSource",
};
var foo = JsonPostAsync(fooAPIData).Result;
Console.WriteLine($"使用 JSON 格式與使用 Post 方法呼叫 Web API 的結果");
Console.WriteLine($"結果狀態 : {foo.Success}");
Console.WriteLine($"結果訊息 : {foo.Message}");
Console.WriteLine($"Payload : {foo.Payload}");
Console.WriteLine($"");
Console.WriteLine($"Press any key to Exist...{Environment.NewLine}");
Console.ReadKey();
fooAPIData = new APIData()
{
Id = 123,
Name = "VulcanSource",
};
foo = JsonPostAsync(fooAPIData).Result;
Console.WriteLine($"使用 JSON 格式與使用 Post 方法呼叫 Web API 的結果");
Console.WriteLine($"結果狀態 : {foo.Success}");
Console.WriteLine($"結果訊息 : {foo.Message}");
Console.WriteLine($"Payload : {foo.Payload}");
Console.WriteLine($"");
Console.WriteLine($"Press any key to Exist...{Environment.NewLine}");
Console.ReadKey();
}