使用AJAX上传图片
使用AJAX上传图片
Html代码:
<body> <form enctype="multipart/form-data"> <div><input type="file" id="MinUpload" /></div> <div><input type="submit" value="提交" /></div> </form> </body>
JS代码:
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js"></script> <script> $(function () { $("form").submit(function () { var MinUpload = $('#MinUpload').get(0).files[0]; //获取上传的文件;//get(0)将Jquery对象转换为DOM对象 var formData = new FormData(); //创建一个formData formData.append('MinUpload', MinUpload); $.ajax({ url: '/Man/Process', method: 'post', data: formData, dataType: 'json', processData: false,//数据处理 contentType: false,//内容类型 cache: false, async: false, success: (result) => { console.log(result); }, error: (error) => { } }) }); }) </script>
控制器代码:
public void Process(HttpPostedFileWrapper MinUpload) { //将图片上传到 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 = Path.GetExtension(MinUpload.FileName); //这里可进行判断是否为 合法的格式文件 string avatorName = Guid.NewGuid().ToString(); MinUpload.SaveAs(dayUrl + "\\" + avatorName + ext); }