• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Asp.Net WebApi上传图片

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
简简单单学习ASP.NET之三发布时间:2022-07-10
下一篇:
ASP.NET 大文件下载的实现思路及代码发布时间:2022-07-10
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap