How to Create ImageOptimize in mvc4(getting error)? - image

Hi all i am working in mvc4 when writing a code for image optimization content showing the error i need to do this any body plz help me to solve this iam getting this error
here is my code:Controllers
public ActionResult Uploading(ImageModel model)
{
var uploadFolder = HostingEnvironment.MapPath("~/App_Data");
uploadFolder = Path.Combine(uploadFolder, DateTime.Now.ToString("yyyy/MM/dd/hh/mm/ss/fff"));
Directory.CreateDirectory(uploadFolder);
var streamProvider = new PreserveFilenameMultipartFileStreamProvider(uploadFolder);
Request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith(t =>
{
foreach (var uploadedFile in Directory.GetFiles(uploadFolder))
{
var medium = Path.Combine(uploadFolder, "medium-" + Path.GetFileName(uploadedFile));
var thumbnail = Path.Combine(uploadFolder, "thumb-" + Path.GetFileName(uploadedFile));
ImageTools.Resize(uploadedFile, thumbnail, 100, 100);
ImageTools.Resize(uploadedFile, medium, 50, 50);
}
return new HttpResponseMessage()
{
Content = new StringContent("File uploaded.")
};
});
return View("Upload", model);
}
and here is my index page :
#using (Html.BeginForm("Uploading", "Upload", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="ImageUploaded" id="btnUpload" multiple="multiple" accept="image/*" />
<button type="submit" id="Upload">Upload</button>
<br />
//#Html.DisplayForModel(#ViewData["Time"]);
<label>#ViewData["Time"]</label>
}
here iam getting an error at Content :HTTPRequestBase doesnot contain defnation for content
Request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith(t =>
could any body help me to solve the problem thanks in advance

Please use the below line in your view:
#using (Html.BeginForm("Action Name", "Controller Name", FormMethod.Post, new { enctype = "multipart/form-data" }))
Because you are uploading the file, you are required to define the above line of code.

Related

Context Disposed Error before DropDownListFor() get populated

I have been trying to get a DropDownList to work:
My controller code is as follows:
public ActionResult Register()
{
var teams = new List<Team>();
using (var context = new TouristContext())
{
teams = (from x in context.Teams select x).ToList();
}
var model = new RegisterViewModel()
{
Teams = new SelectList(teams, "Value", "Text")
};
return View(model);
}
My DropDownListFor() code is as follows:
<div class="form-group">
#Html.LabelFor(m => m.Teams, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.DropDownListFor(m => m.SelectedTeamId, Model.Teams, "Value", "Text")
</div>
</div>
When I try and access the page I get the error:
The operation cannot be completed because the DbContext has been disposed.
I understand the error, but I have no idea how to overcome it.
It turns out the reason it was failing was because I had nothing called Value and Text!
My properties were Id and Name, so I changed my code to:
public ActionResult Register()
{
var teams = new List<Team>();
using (var context = new TouristContext())
{
teams = (from x in context.Teams select x).ToList();
}
var model = new RegisterViewModel()
{
Teams = new SelectList(teams, "Id", "Name")
};
return View(model);
}
And now all works fine.

Error when upload file with Ajax BeginForm HttpPostFileBase alway null

I use Ajax.Beginform menthod to upload file, but it not work, please help me.
File Create.cshtml :
#using (Ajax.BeginForm("UpLoadFile", "KG", new AjaxOptions { HttpMethod = "POST" }, new { enctype = "multipart/form-data", #id = "form-uploadfile" }))
{
<input type="file" name="fileupload" id="fileupload" />
<input type="submit" value="UpLoad" />
}
Controller in server side
[HttpPost]
public ActionResult UploadFile(HttpPostedFileBase fileupload)
{
if (fileupload != null)
{
// Verify that the user selected a file
if (fileupload != null && fileupload.ContentLength > 0)
{
// extract only the fielname
var fileName = Path.GetFileName(fileupload.FileName);
// TODO: need to define destination
var path = Path.Combine(Server.MapPath("~/Upload"), fileName);
fileupload.SaveAs(path);
}
}
return Json(new { success = true });
}
parameter fileupload alway null, i reference many post but still yet solve problem :(
Sorry,My English is very bad

Upload files with Jquery File Upload in ASP.NET MVC 3

Does anyone has a clean suggestion of instantiate this jquery's useful library.
I need to submit files and manage the Json response from the server.
I always get none json response within the Js code. I have reviewed some articles mentioning it but the code doesn't fit to the purpose.
The situation is: I achieve the submition and saving in the database but the Json response never arrives.
Thanks in advance.
This is my view code:
<script type="text/javascript">
$("#formUplImg").fileupload({
dataType: "json",
url:'#Url.Action("CreateJson","ProductImage")',
done: function (e, data) {
alert(data.StatusMessage);
}
});
</script>
#using (Html.BeginForm("CreateJson", "ProductImage", FormMethod.Post, new { id = "formUplImg", enctype = "multipart/form-data", #class = "jqtransform" }))
{
#Html.ValidationSummary(true)
<div class="rowElem">
<input type="file" id="Content" name="Content" />
</div>
<div class="rowElem">
#Html.ValidationMessageFor(item => item.Content)
</div>
<div class="rowElem">#Html.JQueryUI().Button("Guardar imagen", ButtonElement.Button, ButtonType.Submit, new { id = "guardar_imagen" })</div>
}
This is my controller action code:
[HttpPost]
public ContentResult CreateJson(UploadedFileInfo fileInfo)
{
try
{
if (fileInfo.Content == null)
throw new Exception("Hubo problemas con el envĂ­o. Seleccione un archivo a subir");
var file = new TempDocument
{
CreatedBy = User.Identity.Name,
CreationTime = DateTime.Now,
FileName = fileInfo.Content.FileName,
MimeType = fileInfo.Content.ContentType,
Size = fileInfo.Content.ContentLength,
Content = new byte[fileInfo.Content.ContentLength]//Image content to save
};
fileInfo.Content.InputStream.Read(file.Content, 0, fileInfo.Content.ContentLength);//Reading image content into ProductImage object
DocumentsManager.StorePendingDocuments.Add(file);
DocumentsManager.SaveTempDocuments();//Store each document uploaded to: TempDocument Table
TempData["SuccessMsg"] = "The image was saved successfully";
var json = new JavaScriptSerializer().Serialize(new { Success = true, StatusMessage = "El objeto fue insertado correctamente" });
return Content(json, "application/json");
}
catch (Exception exception)
{
TempData["ErrorMsg"] = exception.Message;
var json = new JavaScriptSerializer().Serialize(new { Success = false, StatusMessage = exception.Message });
return Content(json, "application/json");
}
}
Use return type of Action as ActionResult and use:
`return Json(new { Result = "Success" });`
So that on success you will get Json object containing result value.

Modify Content in valums file upload plugins after completion of upload

I am using Valums ajax file-upload plugins for multi file-upload using asp.net mvc 3.
Views
#using (Html.BeginForm("Upload", "AjaxUpload", FormMethod.Post, new { name = "form1", #id="form1" }))
{
#Html.ValidationSummary(true)
<fieldset>
<legend>Upload Wav File</legend>
<div class="editor-label">
#Html.Label("Select Active Date Time")
</div>
<div>
<input type="text" id="active" value="#DateTime.Now" />
</div>
<div class="editor-label">
#Html.Label("Select Language")
</div>
<div>
#Html.DropDownList("Language1", (SelectList)ViewBag.lang)
</div>
<div class="editor-label">
#Html.Label("Select Category")
</div>
<div>
#Html.DropDownList("ParentCategoryID", ViewBag.ParentCategoryID as SelectList)
</div>
<br />
<div id="file-uploader">
<noscript>
<p>Please enable JavaScript to use file uploader.</p>
</noscript>
</div>
</fieldset>
}
Scripts
<script type="text/javascript">
var uploader = new qq.FileUploader
({
element: document.getElementById('file-uploader'),
onSubmit: function () {
uploader.setParams({
param1: document.getElementById("Language1").value,
param2: document.getElementById("ParentCategoryID").value,
param3: document.getElementById("active").value
});
},
action: '#Url.Action("upload")', // put here a path to your page to handle uploading
allowedExtensions: ['jpg', 'jpeg', 'png', 'gif'], // user this if you want to upload only pictures
sizeLimit: 4000000, // max size, about 4MB
minSizeLimit: 0, // min size
debug: true
});
</script>
Controller Action
[HttpPost]
public ActionResult Upload(HttpPostedFileBase qqfile, string param1, string param2, string param3)
{
var filenam = DateTime.Now.ToString("yyyyMMddhhmmss") + param1 + param2 + Request["qqfile"];
var filename = filenam.Replace(" ", "_");
var filepath = Path.Combine(Server.MapPath("~/App_Data/Uploads"), Path.GetFileName(filename));
if (param2 != null || param2 != "")
{
var wav = new PlayWav
{
Name = filename,
CategoryID = int.Parse(param2),
UserID = repository.GetUserID(HttpContext.User.Identity.Name),
LanguageID = int.Parse(param1),
UploadDateTime = DateTime.Now,
ActiveDateTime = DateTime.Parse(param3),
FilePath = filepath
};
db.AddToPlayWavs(wav);
if (qqfile != null)
{
qqfile.SaveAs(filepath);
db.SaveChanges();
return Json(new { success = true }, "text/html");
}
else
{
if (!string.IsNullOrEmpty(filepath))
{
using (var output = System.IO.File.Create(filepath))
{
Request.InputStream.CopyTo(output);
}
db.SaveChanges();
return Json(new { success = true });
}
}
}
return Json(new { success = false });
}
Problems Explaination
I have Upload controller action where I have rename the filename for uploaded file and it is working fine. The problem here is that after file is uploaded, file name displayed the name of original file name and also show the file size. But I want to display the file name which is re-named and the value which is selected in dropdown box list and datetime value submitted from form fields and it's file size is ok. I have no idea how could I modify those content which is displayed after file-upload is completed.
First the new file name is to be returned to clienside as,
assuming filename to be shown is already yielded in the following line,
var filenam = DateTime.Now.ToString("yyyyMMddhhmmss")
+ param1 + param2 + Request["qqfile"];
this needs to be sent to client side,
return Json(new { success = true, filename });
client side code changes, notice the onCompleted event handler, its job is to replace the original filename with the new one received from server.
<script type="text/javascript">
var uploader = new qq.FileUploader
({
element: document.getElementById('file-uploader'),
onSubmit: function () {
uploader.setParams({
param1: document.getElementById("Language1").value,
param2: document.getElementById("ParentCategoryID").value,
param3: document.getElementById("active").value
});
},
onComplete: function (id, fileName, responseJson) {
$(this.element).find('.qq-upload-list li[qqFileId=' + id + ']').find('.qq-upload-file').html(responseJson.filename);
},
action: '#Url.Action("upload")', // put here a path to your page to handle uploading
allowedExtensions: ['jpg', 'jpeg', 'png', 'gif'], // user this if you want to upload only pictures
sizeLimit: 4000000, // max size, about 4MB
minSizeLimit: 0, // min size
debug: true
});
</script>
hope this helps.
EDIT:
qqFileId attribute in the li element is the only associating link bitween the informative li item and uploaded files.
Though the qqFileId is not visible in firebug dom structure, in the console executing the following command shows the id,
$('.qq-upload-list li:last').attr('qqFileId')
if ie browser is causing you the problem it might be because of,
find('.qq-upload-list li[qqFileId=' + id + ']')
and can be changed as
onComplete: function (id, fileName, responseJson) {
$(this.element).find('.qq-upload-list li').each(function () {
if($(this).attr('qqFileId')==id)
$(this).find('.qq-upload-file').html(responseJson.filename);
});
}

How would I pass a value via a ajax form post in MVC3?

I have the ability to upload a file and save it to a directory. That is all good. I need to make an entry to my database with information about that file. So far I am not sure how to pass a value from the view to the controller in this particular case. I have tried to pass it as a method parameter but the value is not getting posted.
Here is my Razor form:
#using (Html.BeginForm("AjaxUpload", "Cases", FormMethod.Post, new { enctype = "multipart/form-data", id = "ajaxUploadForm" }))
{
<fieldset>
<legend>Upload a file</legend>
<label>File to Upload: <input type="file" name="file" />(100MB max size)</label>
<input id="ajaxUploadButton" type="submit" value="Submit" />
</fieldset>
}
<div id="attachments">
#Html.Partial("_AttachmentList", Model.Attachments)
</div>
Here is my jQuery to ajaxify the form:
$(function () {
$('#ajaxUploadForm').ajaxForm({
iframe: true,
dataType: "json",
beforeSubmit: function () {
$('#ajaxUploadForm').block({ message: '<h1><img src="/Content/images/busy.gif" /> Uploading file...</h1>' });
},
success: function (result) {
$('#ajaxUploadForm').unblock();
$('#ajaxUploadForm').resetForm();
$.growlUI(null, result.message);
//$('#attachments').html(result);
},
error: function (xhr, textStatus, errorThrown) {
$('#ajaxUploadForm').unblock();
$('#ajaxUploadForm').resetForm();
$.growlUI(null, 'Error uploading file');
}
});
});
Here is the controller method:
public FileUpload AjaxUpload(HttpPostedFileBase file, int cid)
{
file.SaveAs(Server.MapPath("~/Uploads/" + file.FileName));
var attach = new Attachment { CasesID = cid, FileName = file.FileName, FileType = file.ContentType, FilePath = "Demo", AttachmentDate = DateTime.Now, Description = "test" };
db.Attachments.Add(attach);
db.SaveChanges();
//TODO change this to return a partial view
return new FileUpload { Data = new { message = string.Format("{0} uploaded successfully.", System.IO.Path.GetFileName(file.FileName)) } };
}
I would like cid to be passed to this method so that I can insert a record into the database.
You could include it as a hidden field inside the form:
#Html.Hidden("cid", "123")
or as a route value:
#using (Html.BeginForm(
"AjaxUpload",
"Cases",
new { cid = 123 },
FormMethod.Post,
new { enctype = "multipart/form-data", id = "ajaxUploadForm" }
))
{
...
}

Resources