Multiple file upload association in MVC
I have implemented the File Upload (upon reading Scott Hanselman's excellent post)
I have multiple files associated with various questions on the form though, and 开发者_运维技巧would like to associate each saved file with an internal ID.
How can I do this? For example, if question # 3 has a file uploaded abc.pdf, how can I associated that file with ID #3?
Any good ideas, or has someone done this before?
I would have an array or vector in one of files with a getter and setter. This way when question #3 has file abc.pdf uploaded you can send the information you want to save to the setter and save it at index 3. When you want to access it use the getter for index 3.
Depending what you want to save you create an array that holds what you want. I haven't used Asp.net but this site tells you how to sort an array, which we don't want, but it also shows how to make an array of structures. So if you want to save the name of the file only then you only need a string array. But if you need to save the name and something else then create the array of structures.
Private Structure FileInfo
Public Name As String
Public OtherInfo As String
End Structure
Then create the array with :
Dim FileInfoArray(NumOfPotentialUploadedFiles - 1) As FileInfo
Since it sounds like each of your input fields upload one file each you would just need to remember the id number of the fields and then you would easily "know which IDs the uploaded files were associated with" as if field 1 has an uploaded file then it would be in the array at the same position. You could create a boolean within the structure that is set to false when you first create the array. Then when you upload a file of index 1 you change the boolean to true. This way you easily know which files you have when you go through the array b/c only the positions with a true value have a file.
Ok, figured out an easy solution. I was struggling since the Request.Files[x] object did not have any reference to the fields, but the Request.Files (HttpFileCollectionWrapper) has an AllKeys property that holds the array of fields. My code now is:
for (int fileIndex = 0; fileIndex < Request.Files.Count; fileIndex++)
{
string fieldName = Request.Files.AllKeys[fileIndex]; <--- Here is where you can gleam an key to persist to the database, I have an ID in the fieldName
string savedFileName = Path.GetFileName(Request.Files[fileIndex].FileName);
var path = Path.Combine(<your server save path>, savedFileName);
Request.Files[fileIndex].SaveAs(path);
}
Easy enough!
精彩评论