在C#中利用plupload插件进行http文件上传

这一块是很苦逼的啦,关联性很多,需要改动的也跟多,不过只要想到了很多东西大家可以百度到,好啦,不说废话了。。。。。

一 .  先说一说配置吧,毕竟插件用的再溜,理解的再深刻没配置好那也是白搭。

可能是由于安全性吧,web.config中默认的上传文件的大小为4096KB,也就是差不多4M吧,相对于一般的文本文件还是可以得,毕竟文字占内存小,但是稍微还算有点分量的图片就不够了。所以需要更改上传文件的大小,如下:


先在web.config中找到<system.web>标签,然后在<system.web>标签中找到<httpRuntime>标签,在<httpRuntime>标签中加上executionTimeout="XXXX" maxReuquestLength="XXXXXX",在这解释一下添加的这两个东西的意思:

(1)executionTimeout="XXXX":设置asp.net超时时间,单位:S(秒),说的直白点就是上传文件的时间不能超过这个时间,一旦超过了就报错。

(2)maxReuquestLength="XXXXXX":设置上传文件的大小,单位:KB


    注意:可能有时候设置了上传文件的大小也不一定管用,那么就需要修改IIS中上传文件大小的限制了,具体如下:
(1)首先,关掉iis进程,即把inetinfo.exe进程关掉。(别找错了是进程,不是服务,所以在windows管理器中
(2)在C盘中找到:windows/system32/inesrv/metabase.xml”文件,打开,Ctrl+F 找到AspMaxRequestEntityAllowed="204800"这一项,即iis上传文件的默认大小,默认为204800Byte,也就是200KB,将它修改为合适的大小即可。

二   .配置好了,那咱就说一下插件吧

Plupload中文帮助文档:http://www.phpin.net/tools/plupload/

另还有一个良心的代码:http://pluploadmvc4demo.codeplex.com/SourceControl/latest


有不懂得可以参考上边两部分,我直接上代码了

<table id="filetable">

       <tr>

             <th class="自己定义了">文件名<th>

             <th class="自己定义了">大小<th>

             <th class="自己定义了">状态<th>

             <th class="自己定义了">&nbsp;<th>

      <tr>

</table>


<div id="container">
       <a id="pickfiles" href="javascript:;">[Select files]</a>
       <a id="uploadfiles" href="javascript:;">[Upload files]</a>
</div>

   <br />

    <script type="text/javascript">


     function fremove(a){

          uploader.removeFile($(a).parent().parent()[0].id);

          $(a).parent().parent().remove();

}
    <pre id="console"></pre>

        // Custom example logic

       var uploader = new plupload.Uploader({
           runtimes: 'html5,flash,silverlight,html4',
           browse_button: 'pickfiles', // you can pass in id...
           container: document.getElementById('container'), // ... or DOM Element itself
           url: '../../api/Upload',//注意一下这地方,待会说
           flash_swf_url: 'Scripts/Moxie.swf',
           silverlight_xap_url: 'Scripts/Moxie.xap',
           multipart_params:{"IP":"XXX.XXX.XXX.XXX","savePath":"d:"},//上传的时候带的参数,可以根据需求自己设置

           multipart:true,

           dragdrop:true,
            filters: {
               max_file_size: '10mb',//一般可为KB,MB,GB
                mime_types: [//可上传的类型,title仅仅只是代表一个上传类型的名字
                   { title: "Image files", extensions: "jpg,gif,png" },
                   { title: "Zip files", extensions: "zip" }
               ]
           },

           init: {
               PostInit: function () {
                   document.getElementById('filelist').innerHTML = '';

                   document.getElementById('uploadfiles').onclick = function () {
                       uploader.start();
                       return false;
                   };
               },

               FilesAdded: function (up, files) {
                   plupload.each(files, function (file) {
                       //document.getElementById('filelist').innerHTML += '<div id="' + file.id + '">' +


                       //file.name + ' ('+plupload.formatSize(file.size) + ') <b></b></div>';

                        var rowdata='<tr id="'+file.id+'"><td>'+file.name+'</td><td>('+plupload.formatSize(file.size)+

                         ')</td><td><b></b></td><td style="width:30px;"><a href="#" onclick="fremove(this);">'+

                        '<span>删除</span></a></td></tr>';
                    });
               },

               UploadProgress: function (up, file) {
                   document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>";
               },

               Error: function (up, err) {
                   document.getElementById('console').innerHTML += "\nError #" + err.code + ": " + err.message;
               }
           }
       });

       uploader.init();


后台UploadController:

public class UploadController:ApiController//必须继承这个控制器

{

      public HttpResponseMessage Upload()

        {

              string savePath="";

              if(HttpContext.Current.Request.Form["savePath"]!=null &&

                      HttpContext.Current.Request.Form["savePath"]!="")

                   {

                         savePath=HttpContext.Current.Request.Form["savePath"].ToString();

                   }

             if(HttpContext.Current.Request.Files.Count>0)

                   {

                         if(!Directory.Exists(savePath))

                           {

                                  Directory.CreateDirectory(savePath);

                           }

                         string exp="";

                         HttpPostedFile files=HttpContext.Current.Request.Files[0];  

                         exp=Path.GetExtension(file.FileName);

                         string newFileName=file.FileName;

                         //string fileSize=(file.ContentLength/1024).ToString();//文件大小

                         newFileName=DateTime.Now.ToString("yyyyMMddHHmmss")+"_V1.0"+exp;

                         file.SaveAs(savePath+"\\"+newFileName);   

                         HttpContext.Current.Response.ContentType="text/plain";

                         var serialzer=new System.Web.Script.Serialization.JavaScriptSerializer();

                         var result=new{name=""};

                         HttpContext.Current.Response.Write(serialzer.Serialize(result));

                         HttpContext.Current.Response.StatusCode=200;

                         return new HttpResponseMessage(HttpStatusCode.OK);                                            

                   }

                   else

                   {

                         HttpContext.Current.Response.ContentType="text/plain";

                         var serialzer=new System.Web.Script.Serialization.JavaScriptSerializer();

                         var result=new{name="fail"};

                         HttpContext.Current.Response.Write(serialzer.Serialize(result));

                         HttpContext.Current.Response.StatusCode=404;

                         return new HttpResponseMessage(HttpStatusCode.NotFound);


                   }

                  return new HttpResponseMessage(HttpStatusCode.NotFound);

       }

}



下面说一下上面的url,很明显上边的Controller中没有涉及到任何带api的路径,

但是url中添加了api这个路径,这是为什么呢?

因为新建WEB项目的时候会自动添加一个专门用于http的路由,上边的路径添加了api,代码如下

1.在App_Start中一个名字为WebApiConfig的类

    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }

看见了吧,上边的路由默认都添加了api

就说到这里了,希望对大家能有帮助。


阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/houshubin/article/details/53195249
个人分类: C# WEB
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭