如何用JavaScript阻止onchange提交页面刷新并实现无刷新图片上传展示
解决方法
要实现选中图片自动提交到wwwroot、点击Post按钮无刷新展示图片的需求,你需要用AJAX处理文件上传和页面更新,同时阻止表单默认的刷新行为,具体步骤如下:
1. 修改前端代码(HTML + JS)
调整表单结构、阻止默认提交,添加JavaScript处理文件自动上传和图片展示:
<form enctype="multipart/form-data" asp-controller="YourController" asp-action="UploadImage" onsubmit="return false;"> <a href="javascript:void(0);" class="btn btn-icon fs-xl mr-1" data-toggle="tooltip" data-original-title="Attach files" data-placement="top"> <div> <input type="file" id="choose-file" name="formFile" accept="image/*" /> <label for="choose-file"> <i class="fal fa-paperclip color-fusion-300"></i></label> </div> </a> <a href="javascript:void(0);" class="btn btn-icon fs-xl mr-1" data-toggle="tooltip" data-original-title="Insert photo" data-placement="top"> <i class="fal fa-camera color-fusion-300"></i> </a> <button class="btn btn-info shadow-0 ml-auto " id="submit" onclick="addCode()">Post</button> </form> <!-- 图片预览容器 --> <div id="image-preview-container" style="margin-top:15px;"></div> <script> let uploadedImagePath = ''; // 存储上传后的图片访问路径 // 监听文件选择事件,选中后自动上传 document.getElementById('choose-file').addEventListener('change', function(e) { const file = e.target.files[0]; if (!file) return; const formData = new FormData(); formData.append('formFile', file); fetch('/YourController/UploadImage', { method: 'POST', body: formData }) .then(response => response.json()) .then(data => { if (data.success) { uploadedImagePath = data.imagePath; console.log('图片上传成功'); } else { console.error('上传失败:', data.message); } }) .catch(error => console.error('上传出错:', error)); }); // Post按钮点击事件:无刷新展示图片 function addCode() { if (!uploadedImagePath) { alert('请先选择并上传图片'); return; } const previewContainer = document.getElementById('image-preview-container'); // 清空旧预览 previewContainer.innerHTML = ''; // 创建并插入图片元素 const img = document.createElement('img'); img.src = uploadedImagePath; img.style.maxWidth = '400px'; img.style.maxHeight = '400px'; previewContainer.appendChild(img); } </script>
2. 后端ASP.NET Core控制器代码
创建对应控制器方法,接收上传文件并保存到wwwroot,返回图片访问路径:
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using System.IO; public class YourController : Controller { private readonly IWebHostEnvironment _webHostEnvironment; public YourController(IWebHostEnvironment webHostEnvironment) { _webHostEnvironment = webHostEnvironment; } [HttpPost] public IActionResult UploadImage(IFormFile formFile) { if (formFile == null || formFile.Length == 0) { return Json(new { success = false, message = "未选择有效文件" }); } // 确保wwwroot下的Images目录存在 string uploadsFolder = Path.Combine(_webHostEnvironment.WebRootPath, "Images"); if (!Directory.Exists(uploadsFolder)) { Directory.CreateDirectory(uploadsFolder); } // 生成唯一文件名避免覆盖 string uniqueFileName = Guid.NewGuid().ToString() + "_" + formFile.FileName; string filePath = Path.Combine(uploadsFolder, uniqueFileName); // 保存文件到wwwroot using (var fileStream = new FileStream(filePath, FileMode.Create)) { formFile.CopyTo(fileStream); } // 返回图片的相对访问路径 string imagePath = "/Images/" + uniqueFileName; return Json(new { success = true, imagePath = imagePath }); } }
关键说明
- 阻止页面刷新:给表单添加
onsubmit="return false;",避免点击按钮触发默认表单提交行为。 - 自动上传逻辑:监听文件输入的
change事件,选中文件后立即通过AJAX提交到后端,无需等待Post按钮。 - 无刷新展示:点击Post按钮时直接操作DOM,将上传得到的图片路径插入页面容器,全程不刷新页面。
内容的提问来源于stack exchange,提问作者jiya
相关产品推荐
相关产品推荐

