programing

FileUpload 서버 컨트롤을 사용하지 않고 ASP.net 에서 파일 업로드

mailnote 2023. 4. 26. 23:33
반응형

FileUpload 서버 컨트롤을 사용하지 않고 ASP.net 에서 파일 업로드

일반 오래된 파일을 사용하여 ASP.net 웹 양식(v3.5)을 게시하려면 어떻게 해야 합니까?<input type="file" />?

ASP.net 파일 업로드 서버 컨트롤을 사용하는 데 관심이 없습니다.

aspx에서:

<form id="form1" runat="server" enctype="multipart/form-data">
 <input type="file" id="myFile" name="myFile" />
 <asp:Button runat="server" ID="btnUpload" OnClick="btnUploadClick" Text="Upload" />
</form>

코드 뒤:

protected void btnUploadClick(object sender, EventArgs e)
{
    HttpPostedFile file = Request.Files["myFile"];

    //check file was submitted
    if (file != null && file.ContentLength > 0)
    {
        string fname = Path.GetFileName(file.FileName);
        file.SaveAs(Server.MapPath(Path.Combine("~/App_Data/", fname)));
    }
}

OP가 질문에서 설명한 것처럼 서버 측 제어에 의존하지 않는 솔루션이 있습니다.

클라이언트 측 HTML 코드:

<form action="upload.aspx" method="post" enctype="multipart/form-data">
    <input type="file" name="UploadedFile" />
</form>

upload.aspx의 Page_Load 메서드 :

if(Request.Files["UploadedFile"] != null)
{
    HttpPostedFile MyFile = Request.Files["UploadedFile"];
    //Setting location to upload files
    string TargetLocation = Server.MapPath("~/Files/");
    try
    {
        if (MyFile.ContentLength > 0)
        {
            //Determining file name. You can format it as you wish.
            string FileName = MyFile.FileName;
            //Determining file size.
            int FileSize = MyFile.ContentLength;
            //Creating a byte array corresponding to file size.
            byte[] FileByteArray = new byte[FileSize];
            //Posted file is being pushed into byte array.
            MyFile.InputStream.Read(FileByteArray, 0, FileSize);
            //Uploading properly formatted file to server.
            MyFile.SaveAs(TargetLocation + FileName);
        }
    }
    catch(Exception BlueScreen)
    {
        //Handle errors
    }
}

설정해야 합니다.enctype의 속성form로.multipart/form-data그런 다음 업로드된 파일에 액세스할 수 있습니다.HttpRequest.Files수집.

runat 서버 속성과 함께 HTML 컨트롤 사용

 <input id="FileInput" runat="server" type="file" />

그 다음에 asp.net 에서 코드 뒤에

 FileInput.PostedFile.SaveAs("DestinationPath");

관심이 있는 경우 진행 상황을 표시하는 몇 가지 제3자 옵션도 있습니다.

네, 이것은 아약스 포스트 방식으로 받을 수 있습니다.서버 측에서는 httpandler를 사용할 수 있습니다.그래서 우리는 당신의 요구에 따라 어떠한 서버 제어도 사용하지 않습니다.

Ajax를 사용하면 업로드 진행 상황도 표시할 수 있습니다.

파일을 입력 스트림으로 읽어야 합니다.

using (FileStream fs = File.Create("D:\\_Workarea\\" + fileName))
    {
        Byte[] buffer = new Byte[32 * 1024];
        int read = context.Request.GetBufferlessInputStream().Read(buffer, 0, buffer.Length);
        while (read > 0)
        {
            fs.Write(buffer, 0, read);
            read = context.Request.GetBufferlessInputStream().Read(buffer, 0, buffer.Length);
        }
    } 

샘플 코드

function sendFile(file) {              
        debugger;
        $.ajax({
            url: 'handler/FileUploader.ashx?FileName=' + file.name, //server script to process data
            type: 'POST',
            xhr: function () {
                myXhr = $.ajaxSettings.xhr();
                if (myXhr.upload) {
                    myXhr.upload.addEventListener('progress', progressHandlingFunction, false);
                }
                return myXhr;
            },
            success: function (result) {                    
                //On success if you want to perform some tasks.
            },
            data: file,
            cache: false,
            contentType: false,
            processData: false
        });
        function progressHandlingFunction(e) {
            if (e.lengthComputable) {
                var s = parseInt((e.loaded / e.total) * 100);
                $("#progress" + currFile).text(s + "%");
                $("#progbarWidth" + currFile).width(s + "%");
                if (s == 100) {
                    triggerNextFileUpload();
                }
            }
        }
    }

더 리퀘스트.파일 컬렉션에는 파일 업로드 컨트롤에서 가져온 파일인지 수동으로 작성된 파일인지에 관계없이 양식과 함께 업로드된 파일이 포함됩니다.<input type="file">.

따라서 웹 양식 중간에 일반적인 오래된 파일 입력 태그를 작성한 다음 요청에서 업로드한 파일을 읽을 수 있습니다.파일 컬렉션입니다.

다른 사람들이 답을 가지고 있듯이, 요청.파일은 게시된 모든 파일이 포함된 HttpFileCollection이므로 다음과 같은 파일만 해당 개체에 요청하면 됩니다.

Request.Files["myFile"]

그러나 동일한 속성 이름을 가진 입력 마크업이 두 개 이상 있는 경우에는 어떻게 됩니까?

Select file 1 <input type="file" name="myFiles" />
Select file 2 <input type="file" name="myFiles" />

서버 측의 이전 코드 요청입니다.Files["myFile"]는 두 개의 파일 대신 하나의 HttpPostedFile 개체만 반환합니다..net 4.5에서 GetMultiple이라는 확장 방법을 보았지만 이전 버전에는 존재하지 않습니다. 따라서 다음과 같이 확장 방법을 제안합니다.

public static IEnumerable<HttpPostedFile> GetMultiple(this HttpFileCollection pCollection, string pName)
{
        for (int i = 0; i < pCollection.Count; i++)
        {
            if (pCollection.GetKey(i).Equals(pName))
            {
                yield return pCollection.Get(i);
            }
        }
}

이 확장 메서드는 HttpFileCollection에 "myFiles"라는 이름을 가진 HttpPostedFile 개체가 있으면 모두 반환합니다.

HtmlInputFile 컨트롤

저는 이것을 항상 사용해 왔습니다.

//create a folder in server (~/Uploads)
 //to upload
 File.Copy(@"D:\CORREO.txt", Server.MapPath("~/Uploads/CORREO.txt"));

 //to download
             Response.ContentType = ContentType;
             Response.AppendHeader("Content-Disposition", "attachment;filename=" + Path.GetFileName("~/Uploads/CORREO.txt"));
             Response.WriteFile("~/Uploads/CORREO.txt");
             Response.End();

언급URL : https://stackoverflow.com/questions/569565/uploading-files-in-asp-net-without-using-the-fileupload-server-control

반응형