麻豆小视频在线观看_中文黄色一级片_久久久成人精品_成片免费观看视频大全_午夜精品久久久久久久99热浪潮_成人一区二区三区四区

首頁 > 學院 > 開發設計 > 正文

一個簡單的文件服務器實現方案

2019-11-15 02:25:43
字體:
來源:轉載
供稿:網友

一個簡單的文件服務器實現方案

引子

最近公司的系統約來越多,基本上每個系統都需要用到“資源”,以前只是簡單的把“資源”放到Web服務器中,但是這樣的話有一個頭痛的問題----如何去管理“資源”?

想法

現在不是很流行API嘛,大家好像都在整什么面向服務、面向資源、RESTful什么的,據說在與復雜性的斗爭中,人們討論表象化狀態轉移(REST)已成為了一種時尚!我對這些概念也就是知道個大概,但是也不能解釋的很清楚,但是用意和優點還是很明確的!說白了就是各式各樣的“API”,可能我的理解有偏差,還望大家海涵,哈哈!

HTTP中有幾個常見謂詞,分別是GET/POST/PUT/DELETE,這也正是對應了我們經常說到的CRUD,含義就是對一個資源的增刪改查!

那咱能不能來一個文件API呢?實現對一個一個文件的CRUD?

說時遲,那時快

既然有了想法,咱就得開始干了!那么接下來的問題又來了,怎么干?

文件的增刪改查很簡單,基本功唄!

數據格式?字節數組吧,不用轉來轉去,

數據傳輸呢?就跟一般的API一樣走HTTP協議,HTTP請求報文中分為兩個部分:請求頭和請求體,既然這樣,正好符合我們的需求,請求體承載文件流的字節數組,請求頭中附加一些額外的信息!

說到這,基本上大概的“形狀”就有了!那咱就開始干!!!

添加一個Web應用程序作為服務端,WebForms或者Mvc的都可以。我這里演示的是Mvc的!

不廢話,先上代碼(只有上傳操作),待會大概解釋一下。

// ***********************************************************************// PRoject            : Beimu.Bfs// Assembly         : Beimu.Bfs.Web// Author           : iceStone// Created          : 2014年01月03日 10:23//// Last Modified By : iceStone// Last Modified On : 2014年01月03日 10:23// ***********************************************************************// <copyright file="DefaultController.cs" company="Wedn.Net">//     Copyright (c) Wedn.Net. All rights reserved.// </copyright>// <summary></summary>// ***********************************************************************using System;using System.Collections;using System.Collections.Generic;using System.IO;using System.Linq;using System.Security.Cryptography;using System.Web;using System.Web.Mvc;using Beimu.Bfs.Web.Utilities;namespace Beimu.Bfs.Web.Controllers{    /// <summary>    /// 默認控制器.    /// </summary>    /// <remarks>    ///  2014年01月03日 10:23 Created By iceStone    /// </remarks>    public class DefaultController : Controller    {        /// <summary>        /// 身份驗證        /// </summary>        /// <param name="filterContext"></param>        protected override void OnActionExecuting(ActionExecutingContext filterContext)        {            var uid = Request.Headers["bfs-uid"];// Request["uid"];            var pwd = Request.Headers["bfs-pwd"];//Request["pwd"];            if (!(string.IsNullOrEmpty(uid) || string.IsNullOrEmpty(pwd)))            {                var user = new Users();                if (!user.Exist(uid) || user[uid] != pwd)                {                    filterContext.Result = Json(new { Status = 400, Message = "用戶名或密碼不正確" });                    return;                }            }            base.OnActionExecuting(filterContext);        }        /// <summary>        /// 上傳操作.        /// </summary>        /// <remarks>        ///  2014年01月03日 10:23 Created By iceStone        /// </remarks>        /// <returns>ActionResult.</returns>        public ActionResult Upload()        {            #region 批量            //var files = Request.Files;            //if (files == null || files.Count == 0) return Json(new { Status = 101, Message = "" });            //var dict = new Dictionary<int, string>();            //int index = -1;            //foreach (HttpPostedFile file in files)            //{            //    index++;            //    if (file == null || file.ContentLength == 0) continue;            //    var ext = Path.GetExtension(file.FileName);            //    if (!Config.UploadAllowType.Contains(ext)) continue;            //    if (file.ContentLength >= (Config.UploadMaxSize * 1024 * 1024)) continue;            //    string root = AppDomain.CurrentDomain.BaseDirectory;            //    string path = string.Format("{0}/{1}/{2}/{3}", Config.UploadRoot, dir, DateTime.Now.ToString("yyyy"), DateTime.Now.ToString("MM"));            //    string filename = GetStreammd5(file.InputStream) + ext;//Path.GetFileName(file.FileName);            //    file.SaveAs(Path.Combine(root, path, filename));            //    dict.Add(index, Config.SiteUrl + path + filename);            //}            //return Json(dict);             #endregion            string ext = Request.Headers.AllKeys.Contains("bfs-ext") ? Request.Headers["bfs-ext"] : ".jpg";            var dir = Request.Headers.AllKeys.Contains("bfs-dir") ? Request.Headers["bfs-dir"] : Request.Headers["bfs-uid"];            //dir = string.IsNullOrEmpty(dir) ? "common" : dir;            using (var stream = Request.InputStream)            {                //var files = Request.Files;                if (stream.Length == 0) return SetHeaders(104, "上傳文件為空");                if (stream.Length >= (Config.UploadMaxSize * 1024 * 1024)) return SetHeaders(101, "上傳文件過大");                //string root = AppDomain.CurrentDomain.BaseDirectory;                string path = string.Format("/{0}/{1}/{2}/{3}/", Config.UploadRoot, dir, DateTime.Now.ToString("yyyy"), DateTime.Now.ToString("MM"));                string filename = GetStreamMd5(stream) + ext;//Path.GetFileName(file.FileName);                string fullPath = Server.MapPath(path);                if (!Directory.Exists(fullPath))                    Directory.CreateDirectory(fullPath);                //var buffer = new byte[stream.Length];                //stream.Read(buffer, 0, buffer.Length);  //將流的內容讀到緩沖區                //using (var fs = new FileStream(fullPath + filename, FileMode.CreateNew, Fileaccess.Write))                //{                //    fs.Write(buffer, 0, buffer.Length);                //    fs.Flush();                //    //fs.Close();                //}                 //using (var reader=new StreamReader(stream))                //{                //    using (var writer = new StreamWriter(fullPath + filename, false))                //    {                //        writer.Write(reader.ReadToEnd());                //        writer.Flush();                //    }                //}                using (var fs = new FileStream(fullPath + filename, FileMode.Create))                {                    byte[] bytes = new byte[stream.Length];                    int numBytesRead = 0;                    int numBytesToRead = (int)stream.Length;                    stream.Position = 0;                    while (numBytesToRead > 0)                    {                        int n = stream.Read(bytes, numBytesRead, Math.Min(numBytesToRead, int.MaxValue));                        if (n <= 0)                            break;                        fs.Write(bytes, numBytesRead, n);                        numBytesRead += n;                        numBytesToRead -= n;                    }                    fs.Close();                }                return SetHeaders(100, Config.SiteUrl + path + filename);            }            //if (file == null || file.ContentLength == 0) return SetHeaders(103, "上傳文件為空");            //var ext = Path.GetExtension(file.FileName);            //if (!Config.UploadAllowType.Contains(ext)) return SetHeaders(102, "上傳非法文件");            //if (file.ContentLength >= (Config.UploadMaxSize * 1024 * 1024)) return SetHeaders(101, "上傳文件過大");            //string root = AppDomain.CurrentDomain.BaseDirectory;            //string path = string.Format("{0}/{1}/{2}/{3}", Config.UploadRoot, dir, DateTime.Now.ToString("yyyy"), DateTime.Now.ToString("MM"));            //string filename = GetStreamMd5(file.InputStream) + ext;//Path.GetFileName(file.FileName);            //string fullPath = Path.Combine(root, path);            //if (!Directory.Exists(fullPath))            //    Directory.CreateDirectory(fullPath);            //file.SaveAs(Path.Combine(root, path, filename));            //return SetHeaders(100, Config.SiteUrl + path + filename);        }        [NonAction]        public ContentResult SetHeaders(int status, string resault)        {            Response.Headers.Add("bfs-status", status.ToString());            Response.Headers.Add("bfs-result", resault);            return Content(string.Empty);        }        /// <summary>        /// 獲取文件的MD5值        /// </summary>        /// <remarks>        ///  2013年11月28日 19:24 Created By 汪磊        /// </remarks>        /// <param name="stream">文件流</param>
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 日本欧美国产 | 欧美精品一区二区视频 | 99精品国产小情侣高潮露脸在线 | 久久精品视频亚洲 | 精品伊人 | av电影在线观看网站 | 黄色大片大毛片 | 日本不卡二区 | 99欧美精品 | 免费久久久久 | 久久精品国产亚洲7777 | 久久精品亚洲国产奇米99 | 久久精品视频在线免费观看 | 亚洲啊v在线观看 | 成人一级免费视频 | 欧美亚洲黄色 | 久久第四色 | 中文字幕精品在线播放 | 免费观看高清视频网站 | 午夜视频你懂的 | 万圣街在线观看免费完整版 | 色婷婷a | 91av视频大全| 日韩黄色在线播放 | 久久草在线视频国产 | 成人免费在线视频播放 | 黑色丝袜美美女被躁视频 | 国产精品爱久久久久久久 | 黄色大片免费网站 | 超碰人人做人人爱 | xnxx18日本| 福利四区| 免费黄色在线 | 精品一区二区三区免费看 | 免费a级毛片大学生免费观看 | 国产乱淫av | av国产片| 亚洲欧美不卡视频 | 激情久久免费视频 | 亚洲成人中文字幕在线 | 一级做人爱c黑人影片 |