ASP.NET WEBAPI上传图片

根据业务需要,工程上需要提供两种上传图片的功能,第一是在PC端进行图片的上传,然后同时需要api端也能共享图片信息。

目前的解决方案是在webapi中增加一个接口,专门做图片上传处理,这样这个接口返回的是上传后的图片的路径, 然后API和PC都可以调用。

话不多说,直接上代码

using System;
using System.Web.Http;
using System.Net.Http;
using System.Web.Script.Serialization;
using System.Text;
using System.Web;

namespace BlackNails.Controllers
{
    public abstract class WebAPI2BaseController : ApiController
    {
        public HttpContext context = HttpContext.Current;

        public static HttpResponseMessage toJson(Object obj)
        {
            String str;
            if (obj is String || obj is Char)
            {
                str = obj.ToString();
            }
            else
            {
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                str = serializer.Serialize(obj);
            }
            HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };
            return result;
        }
    }
}

这里先提供这个基础的API程序

using BlackNails.Controllers;
using System;
using System.Collections;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using System.Web.Http.Cors;

namespace Apps.WebApi.Controllers
{
    /// <summary>
    /// 上传文件
    /// </summary>
    [EnableCors(origins: "*", headers: "*", methods: "*")]
    public class ImageUploadController : WebAPI2BaseController
    {

        #region 上传文件
        /// <summary>
        /// 通过multipart/form-data方式上传文件
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<Hashtable> PostFile()
        {
            var strPath = "";
            Hashtable hash = new Hashtable();
            try
            {
                // 是否请求包含multipart/form-data。
                if (!Request.Content.IsMimeMultipartContent())
                {
                    throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
                }

                string root = HttpContext.Current.Server.MapPath("/upload/");
                if (!Directory.Exists(HttpContext.Current.Server.MapPath("~/upload/")))
                {
                    Directory.CreateDirectory(HttpContext.Current.Server.MapPath("~/upload/"));
                }

                var provider = new MultipartFormDataStreamProvider(root);

                StringBuilder sb = new StringBuilder();

                // 阅读表格数据并返回一个异步任务.
                await Request.Content.ReadAsMultipartAsync(provider);

                // 如何上传文件到文件名.
                foreach (var file in provider.FileData)
                {
                    string orfilename = file.Headers.ContentDisposition.FileName.TrimStart('"').TrimEnd('"');
                    FileInfo fileinfo = new FileInfo(file.LocalFileName);
                    if (fileinfo.Length <= 0)
                    {
                        hash["status"] = -1;
                        hash["msg"] = "上传出错";
                        hash["data"] = strPath;
                    }
                    else
                    {
                        string fileExt = orfilename.Substring(orfilename.LastIndexOf('.'));
                        String ymd = DateTime.Now.ToString("yyyyMMdd", System.Globalization.DateTimeFormatInfo.InvariantInfo);
                        String newFileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", System.Globalization.DateTimeFormatInfo.InvariantInfo);
                        if (!Directory.Exists(root + ymd))
                        {
                            Directory.CreateDirectory(root + ymd);
                        }
                        fileinfo.CopyTo(Path.Combine(root, ymd + "\\" + newFileName + fileExt), true);
                        sb.Append("/upload/" + ymd + "/" + newFileName + fileExt);
                        strPath = sb.ToString();
                    }
                    fileinfo.Delete();//删除原文件
                }
                hash["status"] = 0;
                hash["msg"] = "上传成功";
                hash["data"] = strPath;
            }
            catch (Exception e)
            {
                hash["status"] = -1;
                hash["msg"] = "上传出错";
                hash["data"] = strPath;
            }
            return hash;
        }
        #endregion 上传文件
    }
}

这里代码都写注释了。

                <form class="form-horizontal form-border" id="addMemberForm">
                    <div class="form-group">
                        <label class="col-sm-3 control-label">姓名</label>
                        <div class="col-sm-6">
                            <input type="text" class="form-control" placeholder="姓名" name="memberName">
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-3 control-label">头像</label>
                        <div class="col-sm-6">
                            <input type="file" class="form-control" placeholder="头像" name="photo">
                            <button class="btn-success" type="button" id="upload">上传</button>
                        </div>
                    </div>
                        <div class="col-sm-offset-8">
                            <span id="addMemberResult"></span>
                            <input type="button" class="btn btn-success btn-3d" id="addMemberBtn" onclick="indexModule.addMember();" value="添加">
                        </div>
                    </div>
                </form>
<script>
$(document).ready(function() {

    $("#upload").click(function() {
        var url = "http://localhost:1593/api/ImageUpload/PostFile";

        var formData = new FormData($("#addMemberForm")[0]);
        $.ajax({
            url: url,
            type: 'POST',
            data: formData,
            async: false,
            cache: false,
            contentType: false,
            processData: false,
            success: function(returndata) {
                console.log(returndata);
            },
            error: function(returndata) {
                console.log(returndata);
            }
        });
    });
});
</script>

这里是html端调用方法的做法。

posted @ 2017-04-10 14:34  Rexcnblog  阅读(1407)  评论(0编辑  收藏  举报