标签:上传 fun input hang code file round form idt
工作记录用
1 大概页面,点击选择按钮,选择文件,填写备注并可以上传前预览,然后点击上传按钮开始上传
2 html+js代码
<h2>Test</h2> <div id="fileList"></div> <span id="file_ct" style="display:none"><input id="file_input" accept="Image/*" type="file" multiple onchange="onFileChange()" /></span> <a href="#" class="buttom btn-small" onclick="document.getElementById(‘file_input‘).click()">选择图片</a> <a href="#" class="buttom btn-small" onclick="Upload()">上传</a> <script type="text/javascript"> var formData; function onFileChange() { formData = new FormData();//清空FormData中的数据 $("#fileList").html(‘‘); // 清空列表 var Upload = document.getElementById("file_input"); var fileList = Upload.files; for (let i = 0; i < fileList.length; i++) { var file = fileList[i]; if ((file.size / 1024 / 1024) > 10) { alert("图片超过10MB,超过限制大小。"); return; } $("#fileList").append("<tr><td>" + file.name + " 备注:<input type=‘text‘ name=‘Remark_After‘ /><img style=‘width:200px;height:200px;‘ id=‘Img_After_" + i + "‘ src=‘‘ alt=‘‘ /><input type=‘button‘ value=‘上传预览‘ onclick=‘preview1(" + i + ")‘/></td></tr>"); formData.append("Image_After_" + i, file); } // 避免第二次点击无效 $("#file_input").remove(); $("#file_ct").append("<input id=‘file_input‘ accept=‘Image/*‘ type=‘file‘ multiple onchange=‘onFileChange()‘ />"); }; function preview1(i) { let reader if (formData.get("Image_After_" + i)) { reader = new FileReader() reader.readAsDataURL(formData.get("Image_After_" + i)) } reader.onload = function (e) { document.getElementById(‘Img_After_‘ + i).src = e.target.result } } function Upload() { var request = new XMLHttpRequest(); request.open(‘post‘, ‘@Url.Content("~/Home/TestUpload")‘, true); request.onload = function (e) { console.log(e); } $("input[name=‘Remark_After‘]").each(function (index, e) { formData.append("Remark_After_" + index, $(e).val()); }); request.send(formData); //发送请求 request.onreadystatechange = function () { //若响应完成且请求成功 if (request.readyState === 4 && request.status === 200) { alert(‘操作成功。‘); } } } </script>
3 C# 后台代码
public void TestUpload()
{
string basePath = HttpRuntime.BinDirectory;
if (!Directory.Exists(Url.Content($"{basePath}/UploadImage")))
{
Directory.CreateDirectory(Url.Content($"{basePath}/UploadImage"));
}
foreach (string fileName in Request.Files)
{
HttpPostedFileBase file = Request.Files[fileName];
// 生成唯一的文件名称,避免同名覆盖
file.SaveAs(Url.Content($"{basePath}/UploadImage/{Guid.NewGuid().ToString()}.{file.ContentType.Split(‘/‘)[1]}"));
}
}
完成 ,再见 th
formdata 是真的好用
通过FormData对象可以组装一组用 [XMLHttpRequest]发送请求的键/值对,它可以更灵活方便的发送表单数据。
标签:上传 fun input hang code file round form idt
原文地址:https://www.cnblogs.com/lixipeng/p/11690199.html