Asp.Net WebApi上传图片

webapi

using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;

namespace cms.Web.API
{
    public class CeshiController : ApiController
    {
        public async Task<IHttpActionResult> PostUpload()
        {
            //检查是否是 multipart/form-data 
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            //设置上传目录
            string root = HttpContext.Current.Server.MapPath("~/upload");
            var provider = new MultipartFormDataStreamProvider(root);

            try
            {
                //读取form data.
                await Request.Content.ReadAsMultipartAsync(provider);

                string urlPic = string.Empty;
                foreach (var file in provider.FileData)
                {
                    //这里获取含有双引号'" '
                    string filename = file.Headers.ContentDisposition.FileName.Trim('"');
                    //获取对应文件后缀名
                    string fileExt = filename.Substring(filename.LastIndexOf('.'));

                    FileInfo fileinfo = new FileInfo(file.LocalFileName);
                    //fileinfo.Name 上传后的文件路径 此处不含后缀名 
                    //修改文件名 添加后缀名
                    string fname = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo);
                    //string newFilename = fileinfo.Name + fileExt;默认文件名guid生成
                    string newFilename = fname + fileExt;
                    //最后保存文件路径
                    string saveUrl = Path.Combine(root, newFilename);
                    fileinfo.MoveTo(saveUrl);
                    urlPic += "/upload/" + newFilename;
                }
                // 获取表单 key-value.
                //foreach (var key in provider.FormData.AllKeys)
                //{
                //    foreach (var val in provider.FormData.GetValues(key))
                //    {
                //        str+=string.Format("{0}: {1}", key, val);
                //    }
                //}
                if (!string.IsNullOrEmpty(urlPic))
                {
                    dynamic data = new { status = true, url = urlPic };
                    return Json<dynamic>(data);
                }
                else {
                    dynamic data = new { status = false, message = "上传失败" };
                    return Json<dynamic>(data);
                }
            }
            catch
            {
                dynamic data = new { status = false, message = "上传失败" };
                return Json<dynamic>(data);
            }
        }
    }
}

html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>webapi上传图片</title>
    <script type="text/javascript" src="Scripts/jquery-1.8.2.js"></script>
</head>
<body>
    <h2>webapi create</h2>
    <div>
        <form name="form1" method="post" enctype="multipart/form-data" action="api/ceshi/PostUpload">
            <div>
                <label for="caption">name</label>
                <input name="name" type="text" />
            </div>
            <div>
                <label for="image1">Image</label>
                <input type="file" name="photo" id="photo" />
            </div>
            <div>
                <input type="button" value="ajax upload" id="btnUpload" />
            </div>
            <div>
                <img id="phptoPic" width="200" />
            </div>
        </form>
    </div>
    <script type="text/javascript">
        $(function () {
            $("#btnUpload").click(function () {
                var formData = new FormData();
                formData.append("photo", $("#photo")[0].files[0]);
                formData.append("service", 'App.Passion.UploadFile');
                formData.append("token", "123");
                $.ajax({
                    url: 'api/ceshi/PostUpload',
                    type: 'post',
                    data: formData,
                    contentType: false,
                    processData: false,
                    success: function (res) {
                        //console.log(res);
                        if (res.status) {
                            $("#phptoPic").attr("src", res.url)
                        } else {
                            alert(res.message)
                        }
                    }
                })
            })
        })
    </script>
</body>
</html>

 webapi下载文件教程:https://www.cnblogs.com/webapi/p/10540916.html

posted @ 2019-03-16 13:53  WebApi  阅读(4678)  评论(0编辑  收藏  举报
CopyRight © 博客园 WebAPI