最近在写手机端接口文件上传时,需要将写好的接口进行测试,写了个测试例子。主要功能是通过Ajax提交上传文件,后台将文件转为二进制 后,返回给前台,再调用另一个WEBAPI接口。网上查询了一些方法,在此感谢善于总结并把知识共享的人!
前台代码:
<head>
<meta name="viewport" content="width=device-width" />
<title>文件上传测试</title>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.form.js"></script>
<script type="text/javascript">
//使用jquery.form.js脚本,使用ajaxSubmit进行表单提交
function fileUploadMethod1() {
$("#formFileUpload").ajaxSubmit({
success: function (data) {
mobileFileUpload(data);
}
}).fail(
function (xhr, textStatus, err) {
alert('Error: ' + err);
});
}
//不引用脚本,使用jquery的Ajax进行提交
//注:这个方法可以参考原文地址:http://www.jianshu.com/p/46e6e03a0d53
function fileUploadMethod2() {
var odata = new FormData($("#formFileUpload")[0]);
$.ajax({
contentType: false,
cache: false,
processData:false,
url: 'filetest/UploadFile',
dataType: "json",
async: false,
type:"post",
data: odata ,
success: function (data) {
mobileFileUpload(data);
}
}).fail(
function (xhr, textstatus, err) {
alert('error: ' + err);
});
}
function mobileFileUpload(fileData) {
$.ajax({
url: "../api/File/PostFileUpload",
type: "post",
dataType: "json",
data: fileData,
success: function (data) {
if (data == "true")
alert('文件传送成功');
else
alert('文件传送失败');
}
}).fail(
function (xhr, textStatus, err) {
alert('Error: ' + err);
});
}
</script>
</head>
<body>
<div>
@using (Html.BeginForm("UploadFile", "FileTest", FormMethod.Post, new { enctype = "multipart/form-data", id = "formFileUpload" }))
{
<input type="file" value="请选择文件" id="fileUpload" name="fileUpload" />
<input type="button" value="上传" οnclick="fileUploadMethod2()" />
}
</div>
</body>
</html>
后台获取方法:
public string UploadFile()
{
HttpPostedFileBase hpf = Request.Files["fileUpload"]; //主要是这个地方获取到值就没问题了
string fileName = hpf.FileName;
string basePath = "/Temp/" + Guid.NewGuid().ToString() + "/";
if (!Directory.Exists(Server.MapPath(basePath)))
Directory.CreateDirectory(Server.MapPath(basePath));
string fullPath = basePath + fileName;
hpf.SaveAs(Server.MapPath(fullPath));
string binaryString = MyCommon.FileToBinary(Server.MapPath(fullPath));
FileModel model = new FileModel();
model.EventId = "1";
model.FileData = binaryString;
model.FileName = fileName;
model.FileExtension = fileName.Substring(fileName.LastIndexOf("."));
model.Flag = 0;
return JsonHelper.JsonSerializerToString(model);
}