前台:
<div class="control-group">
<label class="control-label">文档文件</label>
<div class="controls">
@*<div id="jquery-wrapped-fine-uploader"></div>*@
<input type="file" name="upfile" id="Files" multiple="multiple" accept="image/*,application/*,text/*,video/*" />
@Html.TextBoxFor(p => p.DocumentMetadata_RemotePath, new { @type = "hidden" })
</div>
</div>
js:
$("#Files", container).change(function (e) {
var target = $(e.target).find("#Files");
$.ajax({
type: "POST",
url: "/MetaData/Upload",
data: null,
beforeSend: function () {
target.prop("disabled",true);
},
success: function (response) {
if (response.success) {
$("#Files", container).replaceWith("<span>" + response.data[0] + "</span>");
$("#metadataform input[name='DocumentMetadata_RemotePath']", container).val(response.data[0]);
}
}
});
});
后台处理:
[HttpPost]
public ActionResult Upload()
{
try
{
string path = ControllerContext.HttpContext.Server.MapPath("~/temp");
string childpath = path + "\\" + currentUser.UserGroup.Name;
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
if (!Directory.Exists(childpath))
{
Directory.CreateDirectory(childpath);
}
Regex re = new Regex(@"\.([^\.]+)$");
List<string> pathlist = new List<string>();
//Request.Files.AllKeys.ToList().ForEach(p =>
//{
// var ext = re.Match(Request.Files[p].FileName).Groups[0].Value;
// var name = DateTime.Now.Ticks.ToString() + "_" + new Random().Next(10000, 100000).ToString();
// Request.Files[p].SaveAs(childpath + "\\" + name + ext);
// pathlist.Add(@"/temp/" + currentUser.UserGroup.Name + "/" + name + ext);
//});
for (int i = 0; i < Request.Files.Count; i++)
{
var ext = re.Match(Request.Files[i].FileName).Groups[0].Value;
var name = DateTime.Now.Ticks.ToString() + "_" + new Random().Next(10000, 100000).ToString();
Request.Files[i].SaveAs(childpath + "\\" + name + ext);
pathlist.Add(@"/temp/" + currentUser.UserGroup.Name + "/" + name + ext);
}
return Json(new { success = true, data = pathlist });
}
catch (Exception)
{
return Json(new { success = false });
}
}
你不要ajax就能实现了。文件是二进制流,不能直接post上去。
好的,谢了,以解决
你没post文件 找个插件试试 例如 uploadify
有post
@using (Html.BeginForm("DocumentView", "MetaData", FormMethod.Post, new { @class = "form-horizontal uni", @id = "metadataform", @enctype = "multipart/form-data" }))
{
@Html.ValidationSummary()
<div class="error-container">
<div class="error-list">
</div>
</div>
<div class="control-group">
<label class="control-label">文档文件</label>
<div class="controls">
@*<div id="jquery-wrapped-fine-uploader"></div>*@
<input type="file" name="upfile" id="Files" multiple="multiple" accept="image/*,application/*,text/*,video/*" />
@Html.TextBoxFor(p => p.DocumentMetadata_RemotePath, new { @type = "hidden" })
</div>
</div>
@情人泪: 你ajax提交部分没post任何数据啊
我想要的效果就是,当我input file选中一个图片后就用onchange事件发送一个post请求到public ActionResult Upload()
@向晚: data:应该是什么数据?
@情人泪: 但是你没post数据 可以试试uploadify这个插件 很好用 可以满足你的需求
@向晚: 我想要的效果是边上传边预览,而且public ActionResult Upload()方法还不能改变,我想把这个问题解决了
jquery form插件中可以解决上传问题