.net 文件上传API

文件上传,支持多文件上传,文件重命名

        public async Task<HttpResponseMessage> PostFile()
        {
            HttpResponseMessage responseMessage = new HttpResponseMessage(HttpStatusCode.NotFound);
            try
            {
                List<string> savedFilePath = new List<string>();
                if (!Request.Content.IsMimeMultipartContent())
                {
                    throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
                }

                //检查上传目录
                var path = AppDomain.CurrentDomain.BaseDirectory;
                string rootPath = System.IO.Path.Combine(path, "upload");
                if (!System.IO.Directory.Exists(rootPath)) System.IO.Directory.CreateDirectory(rootPath);

                //文件操作
                var provider = new MultipartFileStreamProvider(rootPath);

                //多文件异步处理
                responseMessage = await Request.Content.ReadAsMultipartAsync(provider).
                    ContinueWith<HttpResponseMessage>(t =>
                    {
                        if (t.IsCanceled || t.IsFaulted)
                        {
                            Request.CreateErrorResponse(HttpStatusCode.InternalServerError, t.Exception);
                        }

                        foreach (MultipartFileData item in provider.FileData)
                        {
                            try
                            {
                            //文件上传移动处理
                            string name = item.Headers.ContentDisposition.FileName.Replace("\"", "");
                                string newFileName = Guid.NewGuid().ToString("N") + Path.GetExtension(name);
                                File.Move(item.LocalFileName, Path.Combine(rootPath, newFileName));

                            //将路径加入队列
                            string fileRelativePath = "/upload/" + newFileName, //相对路径
                                fileAbsolutePath = rootPath + "\\" + newFileName;//本地文件路径

                            savedFilePath.Add(fileRelativePath);
                            }
                            catch (Exception ex)
                            {
                                string message = ex.Message;
                            }
                        }

                    //设置格式
                    var serializerSettings = new Newtonsoft.Json.JsonSerializerSettings();
                        serializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
                        serializerSettings.ContractResolver = new UnderlineSplitContractResolver();

                        return Request.CreateResponse(HttpStatusCode.Created, JsonConvert.SerializeObject(FrameToResult(savedFilePath), serializerSettings));
                    });
            }
            catch (Exception ex)
            {
                log4net.ILog logger = CustomRollingFileLogger.GetCustomLogger("FileCenterController", "BaseApps");
                logger.Error(ex.Message, ex);
            }
            return responseMessage;
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值