-- 前端代码
<input id="file" type="file" />
<a id="btnRun" href="javasctipt:;">[ 翻 译 ]</a>
<script>
$(function () {
$("#btnRun").click(function () {
$("body").mLoading();
var files = $('#file').prop('files');
var data = new FormData();
data.append('translation_file', files[0]);
$.ajax({
type: "POST",
url: "/Translation/UploadFile",
data: data,
processData: false,
contentType: false,
beforeSend: function (xhr) {
xhr.setRequestHeader("from", $("#ddlFrom option:selected").val());
xhr.setRequestHeader("to", $("#ddlTo option:selected").val());
},
success: function (data) {
alert("OK");
location.href = "DownloadFile?zipPath=" + data;
},
complete: function (XMLHttpRequest, textStatus) {
$("body").mLoading("hide");
},
error: function () {
}
});
});
});
</script>
-- 后端代码 .netcore
[HttpPost]
public string UploadFile()
{
var zipPath = Translation.TranslationBLL.UploadTranslationFile(HttpContext);
return zipPath;
}
-- 上传需要翻译的文件(.zip)
public static string UploadTranslationFile(Microsoft.AspNetCore.Http.HttpContext httpContext)
{
if (httpContext.Request.Form.Files.Count == 0)
return "未检测到文件";
var from = httpContext.Request.Headers["from"];
var to = httpContext.Request.Headers["to"];
/* 创建存储目录 */
if (!Directory.Exists(translationBeforePath))
Directory.CreateDirectory(translationBeforePath);
if (!Directory.Exists(translationAfterPath))
Directory.CreateDirectory(translationAfterPath);
var file = httpContext.Request.Form.Files[0];
string fileExt = file.FileName.Split('.')[file.FileName.Split('.').Length - 1];
if (fileExt.ToLower() != "zip")
return "只能上传zip压缩包";
string filename = Guid.NewGuid().ToString() + "." + fileExt;
string fileFullName = translationBeforePath + "\\" + filename;
using (FileStream fs = System.IO.File.Create(fileFullName))
{
file.CopyTo(fs);
fs.Flush();
}
/* 处理文件 */
var zipFile = ProcessFile(from, to, fileFullName);
/* 输出文件 */
// DownloadFile(httpContext, zipFile);
return zipFile;
}