前端页面:
<input type="file" class="interval" id="fileInput" multiple name="file" />
var files = $("#fileInput").get(0).files;
var fileData = new FormData();
for (var i = 0; i < files.length; i++) {
fileData.append("fileInput", files[i]);
fileData.append("ERPTYPE", "参数1");
fileData.append("TBTYPE", "参数2");
}
$.ajax({
type: "POST",
//url: "/OutAreas/TabFieldTemp/UploadFiles",
url:"http://localhost:51958/CodeManage/UploadFile_Public"
dataType: "json",
contentType: false, // Not to set any content header
processData: false, // Not to process data
data: fileData,
success: function (result, status, xhr) {
console.log(result);
$("#fileInput").val("");//清除文件框
if (result.code == 0) {
}
}
}).fail(function (data) {});
后端接收:
/// <summary>
/// 文件上传公用(测试版本)
/// </summary>
/// <returns></returns>
public string UploadFile_Public()
{
string res = "";
string retStr = "";
try
{
HttpRequest request = System.Web.HttpContext.Current.Request;
HttpFileCollection fileCollection = request.Files;
string ERPTYPE = request["ERPTYPE"];
string TBTYPE = request["TBTYPE"];
string localPath = HttpContext.Server.MapPath("~AllFilesManage/DLLManage/" + ERPTYPE + "/" + TBTYPE + "_" + DateTime.Now.ToString("yyMMddHHmmss") + "/");
string outsidePath = HttpContext.Request.Url.Scheme + "://" + HttpContext.Request.Url.Authority + "/AllFilesManage/DLLManage/" + ERPTYPE + "/" + TBTYPE + "_" + DateTime.Now.ToString("yyMMddHHmmss") + "/";
LogHelper.WriteMessage("*********************DLL文件上传**********************");
LogHelper.WriteMessage("文件数量:" + fileCollection.Count);
LogHelper.WriteMessage("ERPTYPE:" + ERPTYPE);
LogHelper.WriteMessage("TBTYPE:" + TBTYPE);
LogHelper.WriteMessage("ERPTYPE:" + localPath);
LogHelper.WriteMessage("TBTYPE:" + outsidePath);
// 判断是否有文件
if (fileCollection.Count > 0)
{
// 获取文件
HttpPostedFile httpPostedFile = fileCollection[0];
string fileExtension = Path.GetExtension(httpPostedFile.FileName);// 文件扩展名
outsidePath = outsidePath + httpPostedFile.FileName;// 上传路径
// 如果目录不存在则要先创建
if (!Directory.Exists(localPath))//
{
Directory.CreateDirectory(localPath);
}
//保存本地地址后返回外网地址
localPath = localPath + httpPostedFile.FileName;
httpPostedFile.SaveAs(localPath);
retStr = outsidePath;
}
if (!string.IsNullOrEmpty(retStr))
{
res = JsonConvert.SerializeObject(new { code = 1, info = retStr });
}
else
{
res = JsonConvert.SerializeObject(new { code = 0, info = retStr });
}
}
catch (Exception ex)
{
res = JsonConvert.SerializeObject(new { code = 0, Info = ex.Message });
}
return res;
}
webconfig:
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*"/>
<add name="Access-Control-Allow-Headers" value="Content-Type,Token" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
</customHeaders>
</httpProtocol>
</system.webServer>
如果跨域需要:可尝试注释这个节点“<remove name="OPTIONSVerbHandler" />”