标签:ssd file guid val asp formdata process pre oid
HTML:
<form enctype="multipart/form-data"> <p>昵称:<input type="text" id="nickname" /></p> <p>头像:<input type="file" id="avator" /></p> <p><input type="submit" id="submit" value="提交"/></p> </form>
Js:
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js"></script> <script> $(function () { $("form").submit(function () { var nickname = $("#nickname").val(); var avator = $(‘#avator‘).get(0).files[0]; //获取上传的文件;//get(0)将Jquery对象转换为DOM对象 var formData = new FormData(); //创建一个forData formData.append(‘nickname‘, nickname); formData.append(‘avator‘, avator); $.ajax({ url: ‘/Home/Process‘, method: ‘post‘, data: formData, dataType: ‘json‘, processData: false,//数据处理 contentType: false,//内容类型 cache: false, async: false, success: (result) => { console.log(result); }, error: (error) => { } }) }); }) </script>
ASP.Net MVC 后台:
public void Process(string nickname, HttpPostedFileWrapper avator) { //将图片上传到 upload 文件夹下 (upload下,且按照时间存放图片) string baseUrl = AppDomain.CurrentDomain.BaseDirectory + "upload\\"; int year = DateTime.Now.Year; int month = DateTime.Now.Month; int day = DateTime.Now.Day; string dayUrl = baseUrl + year + "\\" + month + "\\" + day; //判断是否存在年月份文件夹,如果不存在则创建 if (!Directory.Exists(dayUrl)) { Directory.CreateDirectory(dayUrl); } //获取拓展名 string ext = System.IO.Path.GetExtension(avator.FileName); //这里可进行判断是否为 合法的格式文件 //... string avatorName = Guid.NewGuid().ToString(); avator.SaveAs(dayUrl + "\\" + avatorName + ext); }
标签:ssd file guid val asp formdata process pre oid
原文地址:https://www.cnblogs.com/licm/p/12910933.html