PromiseAll: async function (array) {
let taskList = [];
let propList = [];
for (let obj of array) {
for (let prop in obj) {
taskList.push(obj[prop]);
propList.push(prop);
}
}
let resp = await Promise.all(taskList);
let result = {};
let counter = 0;
for (let prop of propList) {
result[prop] = resp[counter];
counter += 1;
}
return result;
}
const taskList = [{
adPosition : BannerPositionDataService.GetList(),
big : BannerDataService.GetList(100),
smallTop : BannerDataService.GetOne(200),
smallBottom : BannerDataService.GetOne(300),
section2 : BannerDataService.GetList(400),
section3 : BannerDataService.GetList(500),
section4 : BannerDataService.GetList(600),
recommends : ProductDataService.GetRndList()
}];
let resps = await UJ.PromiseAll(taskList);
DeepBinding: function (vueData, data) {
if (Array.isArray(data)) {
if (!Array.isArray(vueData)) {
vueData = [];
} else {
vueData.splice(0);
}
for (let prop in data) {
vueData.push(data[prop]);
}
}
else if (typeof (data) === 'object') {
if (Object.keys(data).length === 0) {
return;
}
for (let prop in data) {
if (vueData[prop] === undefined || data[prop] === null ||
(!Array.isArray(vueData[prop] && vueData !== null && typeof (data) !== 'object'))) {
vueData[prop] = data[prop];
} else {
this.DeepBinding(vueData[prop], data[prop]);
}
}
} else {
vueData = data;
}
}
UJ.DeepBinding(this, resp);
var root = "C://wdqd/qwewq";
var addPath = @"//\\/fwef/qwf";
var addPath2 = @"5fwfef/qwf";
var addPath3 = @"//fwef/qwf";
var addPath4 = @"\\\fwef/qwf";
var addPath5 = @"\\\\\/fwef/qwf";
var result = root.AddPath(addPath, addPath2, addPath3, addPath4, addPath5);
Console.WriteLine(result);
public static class Helper
{
public static string AddPath(this string value, params string[] addPaths)
{
if (string.IsNullOrEmpty(value))
{
throw new Exception("起始目錄不可以為空字串");
}
if (value.Contains("..") || addPaths.Any(x => x.Contains("..")))
{
throw new Exception($"value: {value}, addPaths: {addPaths.Where(x => x.Contains("..")).ToOneString()} 檔名與路徑不可包含 ..");
}
var paths = addPaths.Select(x => x.Substring(x.FindLastContinuousCharPosition('/', '\\') + 1).SafeFilename()).ToList();
if (paths.Any(x => System.IO.Path.IsPathRooted(x)))
{
throw new Exception("不可併入完整路徑 ..");
}
paths.Insert(0, value.SafeFilename());
return System.IO.Path.Combine(paths.ToArray());
}
public static string ToOneString<T>(this IEnumerable<T> list, string separator = ",")
{
var strList = list.Select(x => x.ToString());
return string.Join(separator, strList);
}
public static int FindLastContinuousCharPosition(this string input, params char[] targets)
{
int lastPosition = -1;
for (int i = 0; i < input.Length; i++)
{
if (targets.Contains(input[i]))
{
lastPosition = i;
}
else
{
break;
}
}
return lastPosition;
}
public static string SafeFilename(this string value)
{
return GetValidFilename(value);
}
public static string GetValidFilename(string value)
{
string ValidFilenameCharacters = @"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\-_$.@:/# ";
if (value.Contains(".."))
{
throw new Exception("路徑中不可包含 .. ");
}
string newUrl = "";
for (int i = 0; i < value.Length; i++)
{
var c = value.Substring(i, 1);
int k = ValidFilenameCharacters.IndexOf(c);
if (k < 0)
{
throw new Exception($"檔名 '{value}' 中有非法的字元 '" + c + "'。");
}
newUrl += ValidFilenameCharacters.Substring(k, 1);
}
return newUrl;
}
}
<a href="http://..." target="_blank" rel="opener">Link</a>
$(".hlkPrint").click(function () {
$("form").setPostDataToStorage();
$("form").attr("rel", "opener");
$("form").attr("target", "_blank");
$("form").attr("action", "xxxxx.aspx");
$("form").submit();
});
public class UploadController : ApiController
{
public async Task<object> PostFormData()
{
var provider = new MultipartMemoryStreamProvider();
if (! Request.Content.IsMimeMultipartContent())
{
return "no file";
}
//要注意這裡的 await
await Request.Content.ReadAsMultipartAsync(provider);
foreach (var content in provider.Contents)
{
if (content.Headers.ContentDisposition.FileName != null)
{
string localFilename = content.Headers.ContentDisposition.FileName.Replace("\"", "");
System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath(@"~/App_Data/Temp/"));
string filename = HttpContext.Current.Server.MapPath(@"~/App_Data/Temp/" + localFilename);
if (System.IO.File.Exists(filename))
{
System.IO.File.Delete(filename);
}
using (var fileStream = new FileStream(filename, FileMode.Create, FileAccess.Write))
{
var contentStream = await content.ReadAsStreamAsync();
await contentStream.CopyToAsync(fileStream);
Trace.WriteLine("Save To" + filename);
}
}
}
return "OK";
}
}
/// <summary>
/// 檔案檢查
/// </summary>
/// <param name="actionContext"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public override async Task OnActionExecutingAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
{
Trace.WriteLine("ApiCheckFile OnActionExecutingAsync");
var request = actionContext.Request;
if (!request.Content.IsMimeMultipartContent())
{
return;
}
var provider = new MultipartMemoryStreamProvider();
await request.Content.ReadAsMultipartAsync(provider);
//把 provider 存入 System.Web.HttpContext.Current.Items 之中,以便在 controller 中再度使用
System.Web.HttpContext.Current.Items["MimeMultipartContentProvider"] = provider;
foreach (var content in provider.Contents)
{
if (content.Headers.ContentDisposition.FileName != null)
{
var filename = content.Headers.ContentDisposition.FileName.Replace("\"", "");
Trace.WriteLine(filename);
var ext = System.IO.Path.GetExtension(filename);
if (!".jpg,.jpeg,.png".Contains(ext.ToLower()))
{
throw new Exception("file format error.");
}
}
}
return;
}
public async Task<object> PostFormData()
{
//改由 HttpContext.Current.Items 中,讀取資料。
MultipartMemoryStreamProvider provider = (MultipartMemoryStreamProvider)System.Web.HttpContext.Current.Items["MimeMultipartContentProvider"];
//如果沒有經過 filter,provider會是 null, 這時就要直接由 Request.Content 讀入 provider
if (provider == null)
{
provider = new MultipartMemoryStreamProvider();
Request.Content.ReadAsMultipartAsync(provider);
}
foreach (var content in provider.Contents)
{
if (content.Headers.ContentDisposition.FileName != null)
{
string localFilename = content.Headers.ContentDisposition.FileName.Replace("\"", "");
Trace.WriteLine("FileName: " + localFilename);
Trace.WriteLine("FileName: " + @"~/App_Data/Temp/" + localFilename);
System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath(@"~/App_Data/Temp/"));
string filename = HttpContext.Current.Server.MapPath(@"~/App_Data/Temp/" + localFilename);
if (System.IO.File.Exists(filename))
{
System.IO.File.Delete(filename);
}
using (var fileStream = new FileStream(filename, FileMode.Create, FileAccess.Write))
{
var contentStream = await content.ReadAsStreamAsync();
await contentStream.CopyToAsync(fileStream);
Trace.WriteLine("Save To" + filename);
}
}
else
{
var contentStream = await content.ReadAsStreamAsync();
var reader = new System.IO.StreamReader(contentStream);
var data = reader.ReadToEnd();
Trace.WriteLine("data: " + data);
}
}
return "OK";
}
public override void OnActionExecuting(ActionExecutingContext actionContext)
{
Debug.WriteLine("MvcCheckFileFilter OnActionExecuting");
if (actionContext.HttpContext.Request.Files.Count > 0)
{
for (int i = 0; i < actionContext.HttpContext.Request.Files.Count; i++)
{
System.Web.HttpPostedFileBase file = actionContext.HttpContext.Request.Files[i];
if (System.IO.Path.GetExtension(file.FileName) != ".jpg")
{
throw new Exception("file format error.");
}
Debug.WriteLine(i + "MvcCheckFileFilter OnActionExecuting File type: " + file.FileName.ToString());
}
}
//以下寫法會發生錯誤: 無法將類型 'System.String' 的物件轉換為類型 'System.Web.HttpPostedFileBase'。
//foreach (HttpPostedFileBase file in actionContext.HttpContext.Request.Files)
//{
// if (System.IO.Path.GetExtension(file.FileName) != ".jpg")
// {
// throw new Exception("file format error.");
// }
//}
}
<script>
var thisPage = {
Init: function () {
thisPage.InitPageInput();
$("body")
;
thisPage.ChangeEvent();
},
ParameterByName: function (targetKey) {
var res = null;
const urlSearchParams = new URLSearchParams(window.location.search);
const params = Object.fromEntries(urlSearchParams.entries());
for (const [key, value] of Object.entries(params)) {
if (targetKey.trim().toLocaleLowerCase() === key) {
res = value;
}
}
return res;
},
OriUrl: function () {
var arrayUrl = [];
arrayUrl.push(window.location.protocol);//https:
arrayUrl.push("//");
arrayUrl.push(window.location.hostname);//blog.uwinfo.com.tw
if (window.location.port.length > 0) {
//大多情況,不用特別指定port
arrayUrl.push(":");
arrayUrl.push(window.location.port);//80
}
arrayUrl.push(window.location.pathname);//post/Edit.aspx
//換一套寫法
//arrayUrl.push(window.location.search);//?Id=321
const urlSearchParams = new URLSearchParams(window.location.search);
const params = Object.fromEntries(urlSearchParams.entries());
var ayyarQueryString = [];
//這邊可以加工增加額外的key值
for (const [key, value] of Object.entries(params)) {
if (value.trim().length > 0) {
//這邊要注意中文需要encode
ayyarQueryString.push(key + "=" + encodeURIComponent(value));
}
}
if (ayyarQueryString.length > 0) {
arrayUrl.push("?");
arrayUrl.push(ayyarQueryString.join('&'));
}
return arrayUrl.length > 0 ? arrayUrl.join('') : '';
},
InitPageInput: function () {
const urlSearchParams = new URLSearchParams(window.location.search);
const params = Object.fromEntries(urlSearchParams.entries());
for (const [key, value] of Object.entries(params)) {
$('input[name=' + key + ']').val(value);
//這邊因為input有多種不同輸入方式,可以自行編輯
//$('select[name=' + key + ']').val(value);
//$('textarea[name=' + key + ']').html(value);
}
},
ChangeEvent: function () {
},
}
$(function () {
thisPage.Init();
});
</script>