MVC异步上传图片到本地/服务器
2016-05-08 16:12
288 查看
这两天朋友问我,有没有异步上传图片到本地/服务器这种demo,他有用, 我就想,好吧, 那刚好周末了,整理一套出来。
主要用到的是jquery uploadify 这个juqery的插件 ,可以无刷新,直接后台上传返回地址
下面先看前台的代码:
后台的代码也很简单:
主要用到的是jquery uploadify 这个juqery的插件 ,可以无刷新,直接后台上传返回地址
下面先看前台的代码:
@{ ViewBag.Title = "Demo"; Layout = "~/Views/Shared/_Layout.cshtml"; } @section styles{ <link href="~/Content/uploadify.css" rel="stylesheet" /> } <h2>Demo</h2> <h2>实例</h2> <div class="form-group"> <input class="form-control" type="file" id="PickImage" name="PickImage" value="浏览图片" /> </div> <div class="form-group"> <img class="img-rounded" id="Rimg" width="200" height="200"/> </div> @section scripts{ <script src="~/Scripts/jquery.uploadify.min.js"></script> <script> jQuery(function () { $('#PickImage').uploadify({ 'swf': '/Content/uploadify.swf', 'buttonText': '选择图片并上传', 'uploader': '@Url.Action("UploadImage","Demo")', 'fileTypeDesc': '图片类型', 'fileTypeExts': '*.jpg;*.jpeg;*.png', "formData": { "folder": "/product/" }, onUploadSuccess: function (localFileObject, serverData, receivedResponse) { console.log(serverData) if (typeof (serverData) == "string") serverData = JSON.parse(serverData); $("#HeadImgurl").val(serverData.ImagePath); $("#Rimg").attr("src", serverData.ImagePath); }, onUploadComplete: function (fileObj) { } }); }); </script> }
后台的代码也很简单:
using System; using System.Collections.Generic; using System.Configuration; using System.IO; using System.Linq; using System.Web; using System.Web.Mvc; namespace Demo_UploadImageToServer.Controllers { public class DemoController : Controller { // GET: Demo public ActionResult Demo() { return View(); } #region 帮助方法 //图片异步上传 public ActionResult UploadImage() { Response.ContentType = "text/plain"; Response.Charset = "utf-8"; HttpPostedFileBase file = Request.Files["Filedata"]; string path = ConfigurationManager.AppSettings["Domain"].ToString(); //填写服务器域名 string basePath = "/UploadPic/"; string uploadPath = Server.MapPath(basePath); //本地路径 if (file != null) { if (!Directory.Exists(uploadPath)) { Directory.CreateDirectory(uploadPath); } string fileName = file.FileName; string ext = fileName.Substring(fileName.LastIndexOf(".")); fileName = DateTime.Now.Ticks + ext; file.SaveAs(uploadPath + fileName); //服务器上传 //return Json(new { ImagePath = string.Format("{0}{1}{2}", path, basePath, fileName) }); //本地上传 return Json(new { ImagePath = string.Format("{0}{1}", basePath, fileName) }); } else { return Json(new { error = 0 }); } } #endregion } }
相关文章推荐
- Git 基础之安装与使用方法介绍
- 理解MVC,MVP和MVVM设计模式
- 对象序列化输出 Serializable
- 设计模式---单例模式
- poj3261最长重复k次子串
- 清北学堂学习总结 day2 字符串 练习
- Permission denied: user=root, access=WRITE, inode="/":hadoopuser:supergroup:drwxr-xr-x
- LVS集群详解(持续更新中)
- 一种排序
- Binary String Matching
- 线程池的原理及实现
- JavaScript之正则表达式
- redis学习笔记(9)---对象robject
- Hadoop重新格式化HDFS的方法
- 个人成就故事
- android java 与C 通过 JNI双向通信
- C经典 宏与typedef的区别
- 单元测试JUnit
- 内存堆和栈的区别
- MySQL 面试中的问题汇总