如何通过Javascript PageMethod将CSV文件上传至ASP.NET WebMethod并解析
ASP.NET PageMethod 实现CSV文件上传并解析处理
你当前的问题核心在于:PageMethod 基于JSON序列化传输数据,直接传递JS的File对象到后台会无法被正确序列化,导致后台收到的object对象是空的或无法解析。下面是可行的解决思路和代码修改方案:
前端代码调整
将File对象转换为Base64字符串(可被JSON序列化的格式)后再传给PageMethod:
<script> // formstone file drop picker library $(".upload").upload({ beforeSend: onBeforeSend }); function onBeforeSend(formData, file) { if (file.name.indexOf(".csv") < 0) { alert("仅支持CSV文件上传"); return false; } // 使用FileReader将文件转为Base64字符串 const reader = new FileReader(); reader.onload = function(e) { // 剥离data URL前缀,仅保留base64编码部分 const fileBase64 = e.target.result.split(',')[1]; PageMethods.set_path("manage-products.aspx"); // 传递文件名和base64内容到后台 PageMethods.UploadCSV(file.name, fileBase64, onSuccess, onFailure); }; // 以DataURL格式读取文件 reader.readAsDataURL(file); function onSuccess(response) { console.log("CSV文件上传处理完成"); } function onFailure(error) { console.log("上传失败:", error.get_message ? error.get_message() : error); } return formData; } </script>
后台WebMethod修改
接收文件名和Base64字符串参数,将Base64转回字节数组后即可处理文件内容:
using System; using System.IO; using System.Web; using System.Web.Services; [WebMethod] public static void UploadCSV(string fileName, string fileBase64) { try { // 将Base64字符串转换为字节数组 byte[] fileBytes = Convert.FromBase64String(fileBase64); // 1. 保存文件到服务器指定目录 string uploadDir = HttpContext.Current.Server.MapPath("~/Uploads/"); // 确保目录存在 if (!Directory.Exists(uploadDir)) { Directory.CreateDirectory(uploadDir); } string savePath = Path.Combine(uploadDir, fileName); File.WriteAllBytes(savePath, fileBytes); // 2. 直接读取CSV内容(无需保存文件) using (MemoryStream ms = new MemoryStream(fileBytes)) using (StreamReader sr = new StreamReader(ms)) { string fullCsvContent = sr.ReadToEnd(); // 这里可以添加CSV解析逻辑,比如按行拆分、处理数据等 // 示例:拆分每行 string[] rows = fullCsvContent.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); } } catch (Exception ex) { // 捕获异常并处理,可通过PageMethod返回错误信息 throw new Exception("文件处理失败:" + ex.Message); } }
关键注意事项
- 确保页面已添加ScriptManager并启用PageMethods:
<asp:ScriptManager ID="ScriptManager1" EnablePageMethods="true" runat="server"></asp:ScriptManager> - 若上传大文件,需修改web.config中的请求大小限制:
<system.web> <httpRuntime maxRequestLength="1048576" /> <!-- 单位KB,这里是1GB --> </system.web> <system.webServer> <security> <requestFiltering> <requestLimits maxAllowedContentLength="1073741824" /> <!-- 单位字节,这里是1GB --> </requestFiltering> </security> </system.webServer> - 对文件名进行安全校验,避免路径注入风险(比如替换特殊字符、限制文件名长度)
内容的提问来源于stack exchange,提问作者Jay
相关产品推荐
相关产品推荐

