1. 程式人生 > >文件上傳的一些記錄

文件上傳的一些記錄

method net ica viewport mda csdn tle style ade

1、js 上傳插件 uploadify、uploadifive(h5版)

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <link href="../../plugins/uploadifive/uploadifive.css" rel="stylesheet" />
</head>
<body>
    <div id="js_logo"> 

    </div>
</body>
</html>

<script src="../../plugins/jquery/jquery.js"></script>
<script src="../../plugins/uploadifive/jquery.uploadifive.js"></script>
<script>
        $(
function () { $(‘#js_logo‘).uploadifive({ ‘buttonClass‘: ‘click‘, ‘buttonText‘: ‘上傳圖片‘, ‘buttonClass‘: ‘.btn btn-success‘, ‘fileType‘: ‘*.jpg, *.jpeg, *.png‘, ‘multi‘: false, ‘uploadScript‘: ‘http://localhost:2145/api/upload/handlerall‘,
"onUploadComplete": function (file, data) { alert(data.msg) } }); }) </script>

2、後端簡單處理代碼

public ActionResult HandlerAll()
{
    HttpPostedFileBase file = Request.Files["Filedata"];
    string[] fileTypes = { ".png", ".jpg", ".jpeg", "
.gif" }; if (file != null) { string fileName = file.FileName; string ext = System.IO.Path.GetExtension(fileName).ToLower(); //驗證擴展名 if (fileTypes.Contains(ext)) { if ((file.ContentLength / (1024 * 1024)) <= 5) { string newFileName = Guid.NewGuid().ToString().Replace("-", "") + ext; string virtualPath = "/uploads"; //保存到/images/logo string physicalPath = Server.MapPath(virtualPath); file.SaveAs(physicalPath + "/" + newFileName); return Json(new { code = 0, msg = "成功", data = newFileName }); } return Json(new { code = 120000, msg = "單個文件5M以內" }); } return Json(new { code = 120001, msg = "圖片格式錯誤" }); } return Json(new { code = 120002, msg = "fileObjName參數必須為Filedata" }); }

3、通常為方便多項目公用,會封裝成圖片服務器,支持跨域,需要增加一點配置,或者在代碼中設置 response header

  <system.webServer>
    <handlers>
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Methods" value="OPTIONS,POST" />
        <add name="Access-Control-Allow-Headers" value="Content-Type,soapaction" />
      </customHeaders>
    </httpProtocol>
  </system.webServer>

4、web api 處理圖片上傳

/// <summary>
/// 測試,請上傳gif圖片
/// </summary>
[AcceptVerbs("OPTIONS", "POST")]
public async Task<HttpResponseMessage> HandlerAll()
{
    try
    {
        if (Request.Method == HttpMethod.Options)
        {
            return Request.CreateResponse(HttpStatusCode.Accepted);
        }

        if (!Request.Content.IsMimeMultipartContent())
        {

        }

        string savePath = HttpContext.Current.Server.MapPath("/uploads");

        var provider = new CustomMultipartFormDataStreamProvider(savePath);

        await Request.Content.ReadAsMultipartAsync(provider);

        List<string> fileNameList = new List<string>();

        foreach (MultipartFileData fileData in provider.FileData)
        {
            fileNameList.Add(fileData.LocalFileName);
        }

        HttpResponseMessage response = Request.CreateResponse<RESTfulModel>(HttpStatusCode.OK, new RESTfulModel() { Code = 0, Msg = "成功", Data = string.Join(",", fileNameList) });

        //response.Headers.Add("Access-Control-Allow-Origin", "*");
        //response.Headers.Add("Access-Control-Allow-Methods", "OPTIONS,POST");
        //response.Headers.Add("Access-Control-Allow-Headers", "Content-Type,soapaction");

        return response;
    }
    catch (Exception ex)
    {
        return Request.CreateResponse(HttpStatusCode.InternalServerError);
    }
}
/// <summary>
/// 重命名上傳的文件
/// </summary>
public class CustomMultipartFormDataStreamProvider : MultipartFormDataStreamProvider
{
    public CustomMultipartFormDataStreamProvider(string rootPath) : base(rootPath)
    {

    }

    public override string GetLocalFileName(HttpContentHeaders headers)
    {
        //截取文件擴展名
        string ext = Path.GetExtension(headers.ContentDisposition.FileName.Trim(\"));
        string fileName = base.GetLocalFileName(headers).Replace("BodyPart_", "").Replace("-", "");
        return fileName + ext;
    }
}

5、瀏覽器在進行跨域請求時,會進行一次 “預請求”,請求方式為 OPTIONS , 在 mvc 沒有處理時沒有進行針對處理,是由於 mvc 的 Response 實際 是 HttpResponseBase 的實例,對 OPTIONS 請求進行了處理 返回了 202 。

在 預請求 完成後, 會發送正常的 POST 請求,攜帶參數,在 web api 代碼中進行了詳細的處理

6、用瀏覽器查看一下詳細的請求

技術分享

技術分享

需要註意

請求的 Content-Type 技術分享

請求的 正文 技術分享

做過微信公眾號開發的朋友,如果註意過 素材上傳 接口會留意到,那個接口需要的 buffer 就是這個格式

如果對表單原理沒有了解過的朋友可以看這篇文章 http://blog.csdn.net/ybygjy/article/details/5869158

文件上傳的一些記錄