일반 이전 <input type="file" />
을 사용하여 파일을 게시하려면 ASP.net 웹 양식 (v3.5)을 어떻게 구할 수 있습니까?FileUpload 서버 컨트롤을 사용하지 않고 ASP.net에서 파일 업로드
ASP.net FileUpload 서버 컨트롤을 사용하고 싶지 않습니다.
의견을 보내 주셔서 감사합니다.
일반 이전 <input type="file" />
을 사용하여 파일을 게시하려면 ASP.net 웹 양식 (v3.5)을 어떻게 구할 수 있습니까?FileUpload 서버 컨트롤을 사용하지 않고 ASP.net에서 파일 업로드
ASP.net FileUpload 서버 컨트롤을 사용하고 싶지 않습니다.
의견을 보내 주셔서 감사합니다.
:
<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)));
}
}
다음은이 문제를 해결할 수있는 다운로드 가능한 프로젝트가 포함 된 코드 프로젝트 문서입니다. 면책 조항 :이 코드를 테스트하지 않았습니다. http://www.codeproject.com/KB/aspnet/fileupload.aspx
는 asp.net의 Codebehind가에
<input id="FileInput" runat="server" type="file" />
그런 다음 RUNAT 서버 속성과 함께 HTML 컨트롤을 사용
FileInput.PostedFile.SaveAs("DestinationPath");
당신이
를 intrested하는 경우 진행 상황을 보여줍니다 일부 3'rd party 옵션도 있습니다다시 말하지만, 서버 컨트롤로 바뀌고 있습니다. ;) – ahwm
form
의 enctype
속성을로 설정해야합니다.; HttpRequest.Files
컬렉션을 사용하여 업로드 된 파일에 액세스 할 수 있습니다.
내 서버 폼이 마스터 페이지에 있었고 multipart/form-data를 추가 할 수 없었습니다 (이후 모든 페이지에있을 것입니다). 빠르고 손쉬운 해결 방법은 숨겨진 FileUpload 컨트롤을 페이지에 추가하는 것입니다. 그런 다음 WebForms는 multipart/form-data를 자동으로 추가했습니다. Angular2에서 파일 입력을 사용하고 있으며 구성 요소 템플릿에서 서버 컨트롤을 사용할 수 없기 때문에이 작업을 수행해야했습니다. – Jason
Request.Files 컬렉션에는 FileUpload 컨트롤에서 왔는지 또는 수동으로 작성한 <input type="file">
에 관계없이 양식과 함께 업로드 한 파일이 들어 있습니다.
WebForm의 중간에 일반 오래된 파일 입력 태그를 작성한 다음 Request.Files 컬렉션에서 업로드 한 파일을 읽을 수 있습니다. 귀하의 영문에서
영업 이익이 질문에 설명하고있다처럼, 모든 서버 측 컨트롤에 의존하지 않고 솔루션입니다.
클라이언트 측 HTML 코드 : upload.aspx의
<form action="upload.aspx" method="post" enctype="multipart/form-data">
<input type="file" name="UploadedFile" />
</form>
를 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
}
}
위대한, 내 문제도 해결! – Etienne
MyFile.FileName에서 전체 파일 경로를 보내는 HTTPWebRequest 호출을 조심하십시오. WebClient 호출은 파일 이름을 전송합니다. HTTPWebRequest는 MyFile.SaveAs가 실패하도록합니다. 한 고객과 한 고객을 쫓아 다니는 시간 낭비. –
예는 아약스 포스트 방법으로이 문제를 achive 수 있습니다. 서버 측에서는 httphandler를 사용할 수 있습니다. 귀하의 요구 사항에 따라 서버 컨트롤을 사용하지 않습니다.
아약스와 함께 업로드 진행 상황을 표시 할 수도 있습니다.
파일을 입력 스트림으로 읽어야합니다.
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);
}
}
샘플 코드
다른 사람이 대답 바와 같이, Request.Files 게시 된 모든 파일이 들어있는 HttpFileCollection, 당신은이 같은 파일을 해당 객체를 요청해야입니다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();
}
}
}
}
아마도'''fs.close()''를 추가하기위한 힌트를 추가해야합니다. 다른 모든 것들이 IIS 내에서 어떻게 든 열려 있기 때문에 읽을 수없는 파일로 끝날 수도 있습니다. – mistapink
:
Request.Files["myFile"]
그러나 동일한 속성 이름을 가진 두 개 이상의 입력 마크 업이있을 때 어떤 일이 :
Select file 1 <input type="file" name="myFiles" />
Select file 2 <input type="file" name="myFiles" />
위의 코드에서 Request.Files [ "myFile"]은 두 파일 대신 HttpPostedFile 개체 하나만 반환합니다. 나는 GetMultiple라는 .NET 4.5 확장 방법에 보았다하지만 그것을하지 존재 않습니다 prevoious 버전, 그 문제에 관해서 내가 확장 방법을 제안한다 :
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);
}
}
}
이 확장 방법이있는 모든 HttpPostedFile 개체를 반환합니다 HttpFileCollection에 "myFiles"라는 이름이 있으면 존재합니다.
//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();
게시물의 서식을 지정하려면'{}'버튼을 사용하십시오. 지금은 쓰레기 텍스트로 보입니다. – Raju
아 .... 내 newb 일 ... LMAO : –
본질적으로 그들이 원하는하지 않았다, 서버 컨트롤로 바뀝니다 추가'RUNAT = "서버"'필요 @Ronnie 오버 비 –