簡単なファイルhtml+ashxをアップロード

1463 ワード


<form action="upload.ashx" method="post" enctype="multipart/form-data"> <input type="file" name="txtUpload" id="fFile" /> <input type="submit" value=" " id="btnUpload" /> </form>

fileのinputラベル、フォームコミットボタン、post形式で一般プロセッサにコミットされて処理されます.
uploas.ashx:
public void ProcessRequest(HttpContext context)

        {

            context.Response.ContentType = "text/plain";



            //           

            if (context.Request.Files.Count > 0)

            {

                //         ,                 

                HttpPostedFile file = context.Request.Files[0];

                //          

                if (!string.IsNullOrEmpty(file.FileName))

                {

                    //        

                    string extention = Path.GetExtension(file.FileName);

                    //           4               

                    string name = DateTime.Now.ToString("yyyyMMdd") + new Random().Next(1000, 10000) + extention;

                    //         

                    string path = context.Server.MapPath("Uploads/" + name);

                    //    

                    file.SaveAs(path);



                    context.Response.Write("ok");

                }

            }



        }