Webapi文件上传

1/  multipart/form-data方式 

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;

namespace FileUpload.Controllers
{
    [RoutePrefix("api/upload")]
    public class UploadController : ApiController
    {

        [Route("file"), HttpPost]
        public async Task<bool> ImgFromDataUploadAsync()
        {
            if (!Request.Content.IsMimeMultipartContent())
                throw new Exception("is no file");



            //web api 获取项目根目录下指定的文件下
            var root = System.Web.Hosting.HostingEnvironment.MapPath("/Resource/Images");

            //如果路径不存在,创建路径  
            if (!Directory.Exists(root))
                Directory.CreateDirectory(root);

            var provider = new MultipartFormDataStreamProvider(root);

            //文件已经上传  但是文件没有后缀名  需要给文件添加后缀名
            await Request.Content.ReadAsMultipartAsync(provider);

            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 newFilename = fileinfo.Name + fileExt;
                //最后保存文件路径
                string saveUrl = Path.Combine(root, newFilename);
                fileinfo.MoveTo(saveUrl);
            }
            return true;


        }

    }
}

猜你喜欢

转载自www.cnblogs.com/eedc/p/9154856.html