In my view, I want to open a xml file manually with a browse button and then be able to send the content of the xml to a text area with a submit button.
Here is some of my code, but I don't know how to display the xml content in my text area.
View :
#using (Html.BeginForm("OpenFile", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="file" id="file"/>
<input type="submit" value="OK"/> }
#Html.TextAreaFor(x => x.XMLContent, 15, 80, null)<p>
Controller :
[HttpPost]
public ActionResult OpenFile(HttpPostedFileBase file)
{
string content = string.Empty;
// Verify that the user selected a file
if (file != null && file.ContentLength > 0)
{
// extract file path
var filePath = Path.GetFullPath(file.FileName);
using (StreamReader reader = new StreamReader(filePath))
{
content = reader.ReadToEnd();
}
}
return View("Index");
}
You need to pass the xml to the view somehow.
One simple option is to use the dynamic ViewBag.
So before returning the view you could add this:
ViewBag.content = content;
And then, in the view:
#Html.TextArea("TextAreaName", (string)ViewBag.content)
Related
Hey I want to upload picture and save that picture to a folder, and save the name of that picture to DB in addition I am also using model binding for other fields of form. Here is the code in this HttpPostedFileBase file receives null I am also using enctype = "multipart/form-data" in my form.
public ActionResult UmrahPackage(PackagesModel model, , HttpPostedFileBase file)
{
try
{
if (model.ID == 0)
{
String fileName = "";
Pakage pkg = new Pakage();
pkg.Title = model.Title;
pkg.PackageDetail = model.PackageDetail;
pkg.Duration = model.Duration;
if (file != null)
{
fileName = System.Guid.NewGuid().ToString() + System.IO.Path.GetExtension(file.FileName);
string physicalPath = Server.MapPath("~/Images/Uploads" + fileName);
// save image in folder
file.SaveAs(physicalPath);
}}
In addition I am also trying this but I am not be able to understand that how to save image in folder I mean the object instance before SaveAs -> file
if (Request.Files.Count > 0 && String.IsNullOrEmpty(Request.Files[0].FileName) == false)
{
HttpPostedFileBase file;
fileName = System.Guid.NewGuid().ToString() + System.IO.Path.GetExtension(Request.Files[0].FileName);
string physicalPath = Server.MapPath("/uploads/profileimages/") + fileName;
file.SaveAs(physicalPath);
}
My form looks like,
#using (Html.BeginForm("UmrahPackage", "Home", FormMethod.Post, new { enctype = "multipart/form-data"}))
{
#Html.HiddenFor(model => model.ID)
<label>Title:</label>
#Html.TextBoxFor(model => model.Title)
<label>Upload Image</label>
<input type="file" id="imgInp">
<button type="submit" >Create</button>
}
Kindly help me, Thanks.
Your input element name attribute value should match with your parameter name
Since your HttpPostedFileBase parameter name is file, give the same name for your file input.
<input type="file" name="file" />
Now when the form is submitted, model binder will be able to map your submitted form data to your parameter named file
I also suggest you to use Path.Combine instead of string concatenation.
string physicalPath = Path.Combine(Server.MapPath("~/Images/Uploads"), fileName);
I had referred to this link to fix the problem of overwriting previously selected files. But this method has led to another problem. The pictures selected were duplicated. Meaning that if I choose 3 pictures, it would save 6.
The following code is my javascript
<input type="file" id="files" name="files" class="btn" style="color:white" multiple />
function previewImages() {
linebreak = document.createElement("br");
var preview = document.querySelector('#preview');
if (this.files) {
[].forEach.call(this.files, readAndPreview);
}
function readAndPreview(file) {
// Make sure `file.name` matches our extensions criteria
if (!/\.(jpe?g|png|gif)$/i.test(file.name)) {
$('#files').val('');
return alert(file.name + " is not an image");
} else if (file.size > 4194304) {
$('#files').val('');
return alert(file.name + "is larger than 4MB");
} else {
var reader = new FileReader();
reader.addEventListener("load", function () {
var image = new Image();
image.height = 100;
image.title = file.name;
image.src = this.result;
preview.append(image.title);
preview.appendChild(image);
});
reader.readAsDataURL(file);
}
}
}
//document.querySelector('#files').addEventListener("change", previewImages);
$(document).on('change', 'input[type="file"][multiple]', function () {
var $this = $(this);
$this.clone().insertAfter($this);
$this.hide();
});
$(document).on('change', 'input[type="file"][multiple]', previewImages);
I have a very simple view that will prompt a user to select a JSON file and then parse it.
Here is the relevant code from the view...
#using (Html.BeginForm("AddSampleDataJSON", "Event"))
{
<input type="file" name="GetJSONFile" /><br>
<input type="submit" />
}
Here is the method from the controller:
[HttpPost]
public ActionResult AddSampleDataJSON(FormCollection form)
{
string path = ??
using (StreamReader r = new StreamReader(path))
{
string json = r.ReadToEnd();
List<Event> events =
JsonConvert.DeserializeObject<List<Event>>(json);
}
return View();
}
The question then is how do I access the full path so I can send it to the StreamReader to eventually parse the JSON. I don't see it in the FormCollection object.
You won't be able to access the client path to the file. You'll only see the file name.
You should set the encoding to multipart/form-data in your view:
#using (Html.BeginForm("AddSampleDataJSON", "Event", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="uploadedFile" /><br>
<input type="submit" />
}
And in your controller change your input parameter to HttpPostedFileBase, with the parameter name being the same as the name parameter in the form:
[HttpPost]
public ActionResult AddSampleDataJSON(HttpPostedFileBase uploadedFile)
{
using (StreamReader r = new StreamReader(uploadedFile.InputStream))
{
string json = r.ReadToEnd();
List<Event> events = JsonConvert.DeserializeObject<List<Event>>(json);
}
return View();
}
I want to upload Pdf file into my application
So I have ViewModel (I post only relevant code)
public class SubcategoryViewModel
{
public HttpPostedFileBase PdfFile { get; set; }
[DisplayName("PDF")]
public string Pdf { get; set; }
}
Controller:
public async Task<string> CreateSubcategory(SubcategoryViewModel model)
{
string pdf = null;
if (model.Pdf != null)
{
pdf = Guid.NewGuid().ToString().Substring(0, 13) + "_" + model.File.FileName;
model.Pdf = pdf;
var path = Path.Combine(HttpContext.Current.Server.MapPath("~/Content/pdf"), pdf);
model.File.SaveAs(path);
}
var subcategory = new Subcategory
{
Pdf = pdf,
};
db.SubcategoriesList.Add(subcategory);
await db.SaveChangesAsync();
View:
#model Models.ViewModels.SubcategoryViewModel
#using (Html.BeginForm("Create", "Subcategory", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="form-group">
#Html.LabelFor(model => model.Pdf, new { #class = "control-label col-md-2" })
<div class="col-md-10 legend-size">
<input type="file" id="file" name="file" />
</div>
</div>
When I action post I don´t received nothing into model.Pdf, so into if (model.Pdf != null) validation it comes null, and I don´t know why
Anyone have idea why it occurs? Thankyou in advance!
You have 2 main issues. First the name of your file input is name="file", but that does not match the property in your model. It needs to be
<input type="file" name="PdfFile" />
Second, you never generate an input for property string Pdf so in the POST method, it will always be null and therefore the code inside your if (model.Pdf != null) will never be executed. However, what you really want is to save the file if its not null, so the code needs to be
public async Task<string> CreateSubcategory(SubcategoryViewModel model)
{
string fileName = null;
if (model.PdfFile != null && model.PdfFile .ContentLength > 0)
{
fileName = Guid.NewGuid().ToString().Substring(0, 13) + "_" + model.PdfFile.FileName;
string path = Path.Combine(HttpContext.Current.Server.MapPath("~/Content/pdf"), fileName);
model.PdfFile.SaveAs(path);
}
var subcategory = new Subcategory
{
Pdf = fileName ,
};
db.SubcategoriesList.Add(subcategory);
await db.SaveChangesAsync();
Side note: I would also recommend an additional property in your model for the files display name (i.e. the value of model.PdfFile.FileName) so that you can use that in your view rather than displaying the name prefixed with a Guid which would have little meaning to the user. Refer this answer for an example.
I think your problem is you are getting null value in PdfFile property of your model. This is because you have not given name attribute of file upload control same as you property. change name attribute of your file upload control to PdfFile.
<input type="file" id="file" name="PdfFile" />
I want to let the user select a file from his/her computer, and then upload it to Flickr. The point is that, when I upload a custom image from my computer, it all works fine, but when I add an extra field for the input file but program suddenly doesn't work.
Test.cshtml:
#using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<fieldset>
<input type="file" name="file" />
<input type="submit" value="Upload!" />
</fieldset>
}
HomeController.cs:
public ActionResult Upload(HttpPostedFileBase file, FormCollection form)
{
if (Request.QueryString["oauth_verifier"] != null && Session["RequestToken"] != null)
{
// Flickr relevant code...
var tmpFilePath = Server.MapPath("~/App_Data/Uploads/Pictures");
if (file == null || file.ContentLength == 0)
{
return RedirectToAction("Index"); // It keeps hitting this!
}
var filename = Path.GetFileName(file.FileName);
var path = Path.Combine(tmpFilePath, filename);
if (System.IO.File.Exists(path))
{
System.IO.File.Delete(path);
}
file.SaveAs(path);
string photoId = flickr.UploadPicture(path, "Test picture");
if (String.IsNullOrEmpty(photoId))
{
System.Diagnostics.Debug.WriteLine("Upload failed!");
}
System.IO.File.Delete(path);
}
else
{
// Flickr relevant code...
}
return View("Test");
}
As long as I know, because MVC is a server-side framework, first of all I need to upload the picture to my server, and then upload it to Flickr. The point is that, I want to put the file in my App_Data/Upload/Pictures folder, and then upload it to Flickr, and afterwards delete it from there. So, I want to keep my server clean.
UPDATE: It keeps hitting the return RedirectToAction("Index"); part, and redirects.
You're missing enctype="multipart/form-data" from you form tag. Without that, file data is not uploaded to the server when the form is submitted.
Change your form call to:
#using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
I am using kendo mobile to build a mobile application in which the user will be able to click and upload a photo. When they first enter the page, it will show their current photo, I want to be able to click and open file explorer on their device and have the ability to show a preview of their photo in place of the old one. Then when the click done it will send it to my MVC controller where I can then send it to where I want. I cant figure out how to send my file to the controller.
HTML
<div id="NewAccountUploadContainer">
<img id="NewAccountUpload" src="~/Images/btnCamera.png" data-bind="click: uploadPhoto" />
#using (Html.BeginForm("SendNewPhoto", "MobilePlatform", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input id="ImageUploadBtn" style="display: none" type="file" accept="image/*" />
<input type="submit" value="OK" style="display: none" />
}
<div id="ImgUploadTxt" data-bind="click: uploadPhoto">
Upload a<br />
different photo.
</div>
The #ImageUploadBtn will be triggered by the #NewAccountUpload or #ImgUploadTxt clicks in jquery which works, but I cant get it to display a file or send to my controller when I trigger the submit.
C# Controller
[HttpPost]
public ActionResult SendNewPhoto(HttpPostedFileBase file)
{
// Verify that the user selected a file
if (file != null && file.ContentLength > 0)
{
// extract only the fielname
var fileName = Path.GetFileName(file.FileName);
// store the file inside ~/App_Data/uploads folder
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
file.SaveAs(path);
}
// redirect back to the index action to show the form once again
return RedirectToAction("Index");
}
The file is always null at this point.
I'm using the Kendo for mvc4, and a mobile implementation, and I'm using the follow code, works for me:
View:
#(Html.Kendo().Upload()
.Name("files")
)
Controller
public ActionResult Submit(IEnumerable<HttpPostedFileBase> files)
{
if (files != null)
{
TempData["UploadedFiles"] = GetFileInfo(files);
}
return RedirectToAction("Result");
}
public ActionResult Result()
{
return View();
}
private IEnumerable<string> GetFileInfo(IEnumerable<HttpPostedFileBase> files)
{
return
from a in files
where a != null
select string.Format("{0} ({1} bytes)", Path.GetFileName(a.FileName), a.ContentLength);
}