简体   繁体   中英

Cannot read file uploaded in c# handler

I'm trying to upload a file to a handler in c# but it seems as though the file is not getting uploaded. Calling Request.Files["fileNameHere"] returns null

My html code:

<form id="importManagerForm" action="../ImportManager.ashx" method="POST">
   <input name="selectedFile" id="selectedFile" type="file" /> 
   <input type="submit" value="submit"/>
</form>

And the code in the ashx handler is:

public void ProcessRequest(HttpContext context)
{
  var importFile = context.Request.Files["selectedFile"]; //This part returns null
  var fileName = new Guid().ToString() + ".csv";
  importFile.SaveAs(fileName);
}

Any idea what's the problem?

UPDATE:

A quick debug on context.Request.Files showed me a file count of 0.

好像您在enctype="multipart/form-data"缺少enctype="multipart/form-data"属性。

You are using the html form control instead of the asp.net form server control.

You will need to set the enctype

<form id="importManagerForm" enctype="multipart/form-data" 
      action="../ImportManager.ashx" method="POST">

Only then will you be able to receive files

Whenever we have a file to be uploaded in html form or whenever we are using tag in the form we have to notify the browser that the request contains binary data. Hence it achieve this you have to add a enctype attribute to the tag.

enctype="multipart/form-data" should be added to form.

it denotes that no characters are encoded before sent. ie it ensure that no character is encoded before sending the data to the server.

The browser may be the cause. If you are using IE the files will be in Request.Files , but in Chrome and FF the files are in Request.QueryString["qqfile"] Here's an example with code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM