概述
前端
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
<input type="file" id="myphoto" />
<div style="display:none" id="div_div1">
<img src="#" id="img_myphoto" />
</div>
</body>
</html>
<script src="assets/js/jquery-1.7.1.js"></script>
<script type="text/javascript">
$("#myphoto").change(function () {
var file = this.files[0];
var formData = new FormData();
formData.append('tFile', file);
jQuery.support.cors = true;
$.ajax({
type: "POST", // 必须用post
url: "http://118.200.100.100:8080/uploadStudentIDCard.ashx?studentID=100",
crossDomain: true,
data: formData,
contentType: false,
processData: false,
success: function (data) {
if (data.result == 1) {
$("#img_myphoto").attr("src", "http://114.215.198.241:8086" + data.url);
$("#div_div1").show();
}
},
error: function (res) {
alert('shit');
}
});
});
</script>
后端:
using JSXiangYu.JiSuJob.BLLFactory;
using JSXiangYu.JiSuJob.IBLL;
using JSXiangYu.JiSuJob.Utility;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Web;
namespace JSXiangYu.JiSuJob.WebApp.student.person
{
public class ResultData
{
public int _result;
public string _msg;
}
/// <summary>
/// uploadStudentIDCard 的摘要说明
/// </summary>
public class uploadStudentIDCard : IHttpHandler
{
IBLLSession bllSession = BLLSessionFactory.CreateBLLSession();//获取业务逻辑会话对象
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "Application/json";
UploadStudentIDCard(context);
}
/// <summary>
/// 上传学生证
/// </summary>
/// <param name="context"></param>
private void UploadStudentIDCard(HttpContext context)
{
context.Response.AddHeader("Access-Control-Allow-Origin", "*");
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, Accept,X-Requested-With");
HttpContext.Current.Response.End();
}
//1.采集数据
//string kk = context.Request.Params["jsoncallback"];
string studentIDStr = context.Request.Params["studentID"];//学生编号
HttpPostedFile file = context.Request.Files["tFile"];//学生证
//2.数据校验
int studentID;
if (!int.TryParse(studentIDStr, out studentID))
{
context.Response.Write("{"result":2}");//学生编号格式有误(学生未登录)
context.Response.End();
return;
}
if (file == null)
{
context.Response.Write("{"result":3}");//未上传学生证
context.Response.End();
return;
}
//3.处理业务逻辑
//3.1处理存储文件的路径
string fileName = Path.GetFileName(file.FileName);//文件的全名称
string ext = fileName.Substring(fileName.LastIndexOf('.'));//文件的扩展名
string dateBasePath;//保存身份证的相对路径
string dateBasePath_m;//手机展示相对路径
string path_m;//手机展示物理路径
string guidStr = Guid.NewGuid().ToString() + ext;//图片名称用Guid命名
//3.2物理路径
string path = GetUploadFilePath(out dateBasePath, out dateBasePath_m, out path_m) + guidStr;//物理路径+文件全名称
path_m += guidStr;//物理路径——手机端
//3.3相对路径
dateBasePath += guidStr;//相对路径+文件全名称
dateBasePath_m += guidStr;//相对路径——手机端
//3.4处理图片+上传图片
Bitmap bmBig = new Bitmap(file.InputStream);
FileExt.MakeThumbnail(bmBig, path, 1024, 600);
Bitmap bmBig2 = new Bitmap(file.InputStream);
FileExt.MakeThumbnail(bmBig2, path_m, 336, 240);
//3.5判断学生账号是否存在
IStudentServer _studentServer = bllSession.StudentServer;
if (!_studentServer.IsExistStudentAccount(studentID))
{
context.Response.Write("{"result":4}");//不存在该学生账号
context.Response.End();
return;
}
//3.6更新学生信息
if (_studentServer.UpdateStudentInfoOfStudentIDCard(studentID, dateBasePath, dateBasePath_m))
{
context.Response.Write("{"result":1,"url":"" + dateBasePath_m + ""}");//图片上传成功
context.Response.End();
return;
}
else
{
context.Response.Write("{"result":0}");//图片上传失败
context.Response.End();
return;
}
}
/// <summary>
/// 处理保存学生证的路径
/// </summary>
/// <param name="newPath">相对路径</param>
/// <returns>返回物理路径</returns>
private string GetUploadFilePath(out string newPath, out string dateBasePath_m, out string path_m)
{
DateTime date = DateTime.Now;
string tempPath = date.Year + "/" + date.Month + "/" + date.Day + "/";
string oldPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "assets/img/student/studentIDCard/");//原始路径
oldPath += tempPath;//压缩图片物理路径
path_m = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "assets/img/student/studentIDCard_m/");//原始路径
path_m += tempPath;//压缩图片物理路径——手机端
if (!Directory.Exists(oldPath))
{
Directory.CreateDirectory(oldPath);
}
if (!Directory.Exists(path_m))
{
Directory.CreateDirectory(path_m);
}
newPath = "/assets/img/student/studentIDCard/" + tempPath;//压缩图片相对路径
dateBasePath_m = "/assets/img/student/studentIDCard_m/" + tempPath;//压缩图片相对路径——手机端
return oldPath;
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
按照如上步骤,编写ajax和一般处理程序后,上传文件,还是提示:No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
检查上传的地址,发现ajax中的地址做了重定向,将http转到了https,于是把地址调整为https,发现上传成功。
转载至:https://www.cnblogs.com/fanyongjiu/p/5609707.html
最后
以上就是含蓄外套为你收集整理的asp.net跨域上传文件的全部内容,希望文章能够帮你解决asp.net跨域上传文件所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复