Convert string to HttpPostedFileBase
Solution 1
As mentioned by others, your form should look something like this:
<form id="form_UploadFile" action="" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
</form>
Then as you mentioned you are trying to post via ajax, you can use jQuery serialize() to serialize the formData to be pushed to your controller.
$('#form_UploadFile').serialize();
Solution 2
You can't just pass a string from the UI, you need to upload the file from an input type="file"
.
Solution 3
you have to have your <form>
tag to look like this:
<form action="" method="post" enctype="multipart/form-data">
Then you will receive proper HttpPostedFileBase
object
You may refer to this article regarding all details.
UPDATE
Using ajax to submit form does not make any difference:
@using (Ajax.BeginForm("YourActionName", null, new AjaxOptions { UpdateTargetId = "YourTargetId" }, new { enctype = @"multipart/form-data" }))
{
//Your inputs here
}
Solution 4
Did you remember to use the verbose Html.BeginForm
method?
@using (Html.BeginForm("Attach", "File", FormMethod.Post, new { enctype = "multipart/form-data" })) {
}
The important part is enctype="multipart/form-data"
ZVenue
Your persistence is a measure of faith you have in your abilities.
Updated on June 09, 2022Comments
-
ZVenue almost 2 years
I am trying to do upload attachment functionality using MVC. My method that is actually doing the upload/save attachment is expecting a HttpPostedFileBase type.
public virtual string Upload(HttpPostedFileBase fileName) { //Code to upload/save attachment. }
My problem is "fileName" is being passed from the UI as a string. How can I convert the string(file path name) into something my Upload method can work with.
Thanks in advance.