我稍微解释一下你的问题.. 我会做两个假设:
1)您想上传文件而不发布表单,因此刷新页面,即异步上传
2)您希望能够使用您喜欢的任何按钮启动选择器(这样您就可以按照自己的意愿设置样式)
以下解决方案将在单击按钮时启动文件选择器。可以选择多个文件并将它们异步发布到服务器(AJAX)。
<input type="file" name="attach" id="attach-input" multiple="" style="display:none" />
<button type="submit" name="attach" id="attach-button">Upload</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
var button = $('#attach-button');
var input = $('#attach-input');
// translates collection of files into a form
function BuildFormData(files) {
var data = new FormData();
for (var i = 0; i < files.length; i++) {
data.append(files[i].name, files[i]);
}
return data;
}
// posts the files to a given url
function PostData(url, data) {
$.ajax({
// method
type: 'POST',
// endpoint
url: url,
// next 2 lines required for using FormData with jQuery
contentType: false,
processData: false,
// FormData instance
data: data,
// success handler
success: function (result) {
alert('files uploaded successfully');
console.log(result);
}
});
}
// when the button is clicked..
button.on('click', function (e) {
// it launches the file picker
input.click();
});
// when the file picker changes..
input.on('change', function (e) {
// turn it into a form
var data = BuildFormData(e.target.files);
// post the form to the action method
PostData('/Index/Attach', data);
});
</script>
我在asp.net MVC控制器中使用的action方法会将文件保存到应用程序的App_Data文件夹中:
[HttpPost]
public void Attach()
{
foreach (string file in Request.Files)
{
HttpPostedFileBase fileContent = Request.Files[file];
Stream stream = fileContent.InputStream;
string fileName = Path.GetFileName(file);
string path = Path.Combine(Server.MapPath("~/App_Data"), fileName);
using(var fileStream = System.IO.File.Create(path))
{
stream.CopyTo(fileStream);
}
}
}
希望能引导您朝着正确的方向前进。