最近开发一个上传图片的模块,传图片的接口不支持跨域上传,并且只支持单张上传,而我们的产品要求要实现多张上传。我搞了一个代理页面,先将图片传到代理页面,然后再通过代理页面传到上传图片接口。虽然这种方式经过一个代理页面会增加消耗的时间,但总算解决了跨域上传的问题。现在粘贴我的代码如下,前端脚本:
(function () {
var imgOperate = {
operateUrl: "更改图片在数据库中的状态地址",
uploadUrl: "代理图片上传地址",
DelPicId: '',
ddWidth: 0,
dlWidth:0,
onload: function () {
this.initImage();
},
initImage: function () {
var et = $('#entrust dd').length;
this.ddWidth = $('#entrust dd').width() + 17;
this.dlWidth = parseInt(et * this.ddWidth + 160);
$('#entrust').css("width", this.dlWidth);
this.BindEvent();
},
BindEvent: function () {
var _this = this;
$("#pic0").on("change", function () { _this.uploadFiles(this); }); },
InserImage:function(urls,dd)
{
$.post(this.operateUrl, { houseid: houseid, operateType: 1, picStr: urls }, function (data) {
data = eval("(" + data + ")");
if (data && data.picIds)
{
dd.getElementsByTagName("img")[0].setAttribute("housepicid", data.picIds);
}
});
},
uploadFiles: function (where) { var imgLength = $("#entrust dd").length - 1; if (imgLength >= 50)
{
this.ShowMsg("你的图片超过了50张,不能再上传");
return;
}
if (imgLength + where.files.length > 50)
{
this.ShowMsg("你选择的图片超过了50张,无法上传,请重新选择");
return;
}
var _this = this;
var radtime = new Date();
var _this = this;
var sid = radtime.getTime();
for (var i = 0, successCount=0; i < where.files.length; i++) {
var formData = new FormData(); formData.append("icoimage",where.files[i]); $.ajax({
url:this.uploadUrl+ '?channel=频道&sid=' + sid,
type: 'POST',
cache: false,
data: formData,
processData: false,
contentType: false
}).success(function (res) {
var imgsrc = res;
if (imgsrc == "-1" || imgsrc == "302" || imgsrc == -1 || imgsrc == 302) {
_this.ShowMsg("上传失败,照片超过10M");
} else if (imgsrc.indexOf("http")!=-1) {
var dd = document.createElement("dd");
if ($("#entrust dd").length == 1) {
dd.innerHTML = "<div class=\"cver\">封面图</div><a class=\"close\"></a><img src=\"" + imgsrc + "\" housepicid=\"\">";
} else {
dd.innerHTML = "<a class=\"close\"></a><img src=\"" + imgsrc + "\" housepicid=\"\">";
}
document.getElementById("entrust").appendChild(dd);
_this.dlWidth += _this.ddWidth + 17;
$('#entrust').css("width", _this.dlWidth);
_this.InserImage(imgsrc, dd);
successCount++;
_this.ShowMsg("正在上传第" + i + "张图片");
}
if (i == where.files.length) {
if (successCount > 0) {
_this.ShowMsg("成功上传" + successCount + ",可继续上传新照片");
}
} else {
_this.ShowMsg("上传失败");
} })
} },
ShowMsg: function (text, mymethod) {
var radtime = new Date();
var sid = radtime.getTime();
var msg_div = "<div class='zuopenbox' id='div_msg" + sid + "'><div class='opencon_01'><div class='openList'><h3 class='f15' style='margin-bottom: 0; color: #FFFFFF'>" + text + "</h3></div></div></div>"; $(msg_div).appendTo("body");
var _this = this;
setTimeout(function () {
var d = 0.5;
var m = document.getElementById("div_msg"+sid);
m.style.webkitTransition = '-webkit-transform ' + d + 's ease-in, opacity ' + d + 's ease-in';
m.style.opacity = '0';
setTimeout(_this.RemoveNode(m), 500);
}, 500);
},
RemoveNode: function (m) {
m.parentNode.removeChild(m);
} } imgOperate.onload();
window.imgOperate = imgOperate; })();
前端脚本代码
代理服务器代码:
public override void ProcessRequest(HttpContext context)
{
//获取目标站点地址
String target = "图片服务器地址";
string sid = context.Request["sid"];
target = string.Format("{0}?city=&channel=频道&sid={1}&backurl=",target,sid);
if(context.Request.Files.Count>)
{
var file = context.Request.Files[];
HttpWebRequest request = WebRequest.Create(target) as HttpWebRequest;
CookieContainer cookieContainer = new CookieContainer();
request.CookieContainer = cookieContainer;
request.AllowAutoRedirect = true;
request.Method = "POST";
request.Headers.Add("Origin", "http://" + context.Request.UrlReferrer.Host);
request.Headers.Add("Accept-Encoding", "gzip, deflate");
request.Headers.Add("Accept-Language", "zh-CN,zh;q=0.8");
request.Headers.Add("Upgrade-Insecure-Requests", "");
request.Referer = context.Request.UrlReferrer.OriginalString;
string boundary = DateTime.Now.Ticks.ToString("X"); // 随机分隔线
request.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary;
byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");
byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n"); //请求头部信息
StringBuilder sbHeader = new StringBuilder(string.Format("Content-Disposition:form-data;name=\"file\";filename=\"{0}\"\r\nContent-Type:application/octet-stream\r\n\r\n", file.FileName));
byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sbHeader.ToString());
//FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
byte[] bArr = new byte[file.InputStream.Length];
file.InputStream.Read(bArr, , bArr.Length);
file.InputStream.Close();
Stream postStream = request.GetRequestStream();
postStream.Write(itemBoundaryBytes, , itemBoundaryBytes.Length);
postStream.Write(postHeaderBytes, , postHeaderBytes.Length);
postStream.Write(bArr, , bArr.Length);
postStream.Write(endBoundaryBytes, , endBoundaryBytes.Length);
postStream.Close();
//发送请求并获取相应回应数据
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
SetCookie(response,context);
} }
//response是目标服务器的响应对象,context是返回给浏览器的上下文对象
void SetCookie(HttpWebResponse response, HttpContext context)
{
foreach (Cookie cookie in response.Cookies)
{
if (cookie.Name!=null&&cookie.Name.StartsWith("img"))
{
string result=string.Empty;
if (cookie.Value != null && cookie.Value.StartsWith("http://"))
{
Regex r = new Regex(@"^.*?(?=\|)");
result = r.Match(cookie.Value).Value;
}
else {
result = cookie.Value;
}
context.Response.Write(result);
context.Response.End();
} }
}
因为图片服务器返回的地址是种在cookie当中的,因此代理服务器中我将相应cookie的地址接收予以返回。在开发该功能时我遇到了很多问题,图片接口同事比较忙,无法配合,后来自己模拟相应服务器的接口上传,才发现代理中并没有将文件传上去。经过比较修改,最后才上传成功。