上传图片的功能尝试了一个下午,竟然没有成功,用jquery.form.js 以及 formData 上传出现各种状况,最后找了百度的webupload试一下,神奇的成功了。
上代码。
视图
<link rel="stylesheet" type="text/css" href="~/webupload/webuploader.css"> <script type="text/javascript" src="~/webupload/webuploader.js"></script>
<div id="uploader" class="wu-example"> <input type="hidden" value="hid_blog_image" /><div id="thelist" class="uploader-list"></div> <a href="javascript:void(0)" οnclick="remove_pic()" id="minus"> <span class="glyphicon glyphicon-remove"></span> </a> <!--用来存放文件信息--> <div class="btns"> <div id="picker">选择文件</div> <button id="ctlBtn" class="btn btn-default">开始上传</button> </div> </div>
var BASE_URL = ''; |
后端:
using core_admin.Models;
public class UploadController : Controller {[HttpGet] public IActionResult Index() { return View(); } [HttpPost] public string Upload() { MyResult result = new MyResult(); try { var form = Request.Form; Hashtable hash = new Hashtable(); IFormFileCollection cols = Request.Form.Files; if (cols == null || cols.Count == 0) return "file not selected"; foreach (IFormFile file in cols) { var new_path = Guid.NewGuid() + System.IO.Path.GetExtension(file.FileName); new_path = Path.Combine("uploads/images/", new_path); var path = Path.Combine( Directory.GetCurrentDirectory(), "wwwroot", new_path); using (var stream = new FileStream(path, FileMode.Create)) { file.CopyTo(stream); hash.Add("file", "/" + new_path); } } result.data = hash; result.result = "success"; } catch (Exception ex) { result.err_msg = ex.Message; result.result = "error"; } return JsonConvert.SerializeObject(result); } } |
用到了我的一个类:
public class MyResult { public string result { get; set; } public string err_msg { get; set; } public int total { get; set; } public object data { get; set; } public string page1 { get; set; } public string page2 { get; set; } } |