實現功能
讓 js 用 ajax 的方式傳檔案到跨網域的 server 上,而不會遇到跨網域問題。
核心程式(C#)
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Web;
namespace Tools
{
public class HttpCaller
{
public static string MultipartForm(string url, HttpRequestBase request)
{
var ignoreHeader = new string[] { "Content-Length", "Content-Type", "Host", "Referer" };
string result = string.Empty;
var mediaType = "";
try
{
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Clear();
foreach (var key in request.Headers.AllKeys)
{
if (key.Equals("Content-Type"))
{
mediaType = request.Headers[key];
}
if (ignoreHeader.Contains(key))
{
continue;
}
client.DefaultRequestHeaders.Add(key, request.Headers[key]);
}
HttpRequestMessage message = new HttpRequestMessage(HttpMethod.Post, url);
message.Content = new ByteArrayContent(StreamToBytes(request.InputStream));
message.Content.Headers.Remove("Content-Type");
message.Content.Headers.Add("Content-Type", mediaType);
result = client.SendAsync(message).Result.Content.ReadAsStringAsync().Result;
}
}
catch (Exception ex)
{
result = ex.Message;
}
return result;
}
private static byte[] StreamToBytes(Stream stream)
{
byte[] bytes = new byte[stream.Length];
stream.Read(bytes, 0, bytes.Length);
stream.Seek(0, SeekOrigin.Begin);
return bytes;
}
}
}
使用方法(C# ASP.NET MVC 專案)
public ActionResult upload()
{
var targetUrl = Request.Form["targetUrl"];
var json = HttpCaller.MultipartForm(targetUrl, Request);
return Content(json);
}
使用方法(JS)
function uploadRequest(targetUrl, requestObject, files, callback) {
var formData = new FormData();
for (var key in requestObject) {
formData.append(key, requestObject[key]);
}
for (var i = 0 ; i < files.length ; i++){
formData.append("file" + (i+1), files[i]);
}
formData.append("targetUrl", targetUrl);
var request = new XMLHttpRequest();
request.open("POST", "upload");
request.onload = function (e) {
var response = e.target.response;
callback(response);
};
request.send(formData);
}
沒有留言:
張貼留言