2

Basically, I'm building a website that allows user to upload file. From the front end (JavaScript), the user will browse a file, I can get the site to send POST data (the parameter "UploadInput" and it's value, which the value is the file) In the backend (C#), I want to make a copy of the file and save it in a specific path. Below is the way I did it.

var files = Request.Files; file[0].SaveAs("\temp\\" + file[0].FileName); 

The problem I ran into is that I got the error message saying index out of range. I tried Response.Write(files.Count) and it gives me 0 instead of 1. I'm wondering where I did wrong and how to fix it, or if there's a better way of doing it. Thanks!

Edit:

I am using HttpFox to debug. From HttpFox, I can see that under POST data, parameter is "UploadInput" and the value is "test.txt"

Edit 2: So I tried the way Marc provides, and I have a different problem. I am able to create a new file, however, the content is not copied over. I tried opening the new created file in notepad and all it says is "UploadInput = test.txt"

3
  • How are you posting the data to the server? Did you specify enctype="multipart/form-data" in the form? Commented May 3, 2013 at 22:39
  • @Guffa No, and I'm too sure what you mean by that :/ Commented May 3, 2013 at 22:59
  • The form has to have that attribute for the browser to send uploaded files in a format that the server can use. If you don't have it, the file can't be included in the form data. Commented May 3, 2013 at 23:06

1 Answer 1

2

If they simply posted the file as the body content, then there will be zero "files" involved here, so file[0] will fail. Instead, you need to look at the input-stream, and simply read from that stream. For example:

using(var file = File.Create(somePath)) { Request.InputStream.CopyTo(file); } 
Sign up to request clarification or add additional context in comments.

2 Comments

what would somePath be? is it the URL of the website? the way the site works is the user browse file and hit upload, by using HttpFox I can see under POST data the parameter is "UploadInupt" and the value is "test.txt"
@sora0419 somePath here was the local path on the web-server; however, I think you need to be a little clearer about what the data is that is being posted. Is this multi-part? or raw body? or...?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.