Partial view page for create,edit,delete in asp.net mvc4 - image

How to upload the image in asp.net mvc4.images save in local folder,images path name save to database.

I would say use Valum's AJAX File Uploader
here is how I'd done that
[HttpGet]
public ActionResult PictureUpload()
{
return View();
}
[HttpPost]
public ActionResult PictureUpload( string qqfile)
{
var path = Server.MapPath("~/App_data/Files/");
var file = string.Empty;
try
{
var stream = Request.InputStream;
if (String.IsNullOrEmpty(Request["qqfile"]))
{
// IE
HttpPostedFileBase postedFile = Request.Files[0];
if (postedFile != null) stream = postedFile.InputStream;
file = Path.Combine(path, qqfile);
}
else
{
//Webkit, Mozilla
file = Path.Combine(path, qqfile);
}
var buffer = new byte[stream.Length];
stream.Read(buffer, 0, buffer.Length);
System.IO.File.WriteAllBytes(file, buffer);
}
catch (Exception ex)
{
return Json(new { success = false, message = ex.Message }, "application/json");
}
return Json(new { success = true }, "text/html");
}
**THIS GIVEN HTML and Javascript need uploaderjs file and css file from Valums website **
Index
<div id="file-uploader">
<noscript>
<p>Please enable JavaScript to use file uploader.</p>
<!-- or put a simple form for upload here -->
</noscript>
</div>
<script src="~/Scripts/fileuploader.js"></script>
<script type="text/javascript">
var uploader = new qq.FileUploader({
// pass the dom node (ex. $(selector)[0] for jQuery users)
element: document.getElementById('file-uploader'),
// path to server-side upload script
action: '/FileUpload/File',
onComplete: function(data) {
alert(data);
},
});
</script>
Hope this will help

Related

How to retrieve uploaded file using ajax on java server side?

I am using struts2 framework on server side. I am uploading a file using
server side :
<s:file name="fTU" id="fTU"/>
<input type="submit" value ="ok" onclick="upload()">
client side :
function upload(){
var file = document.getElementById("fTU");
try {
this.xml = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
this.xml = new ActiveXObject("Microsoft.XMLHTTP");
} catch (err) {
this.xml = null;
}
}
if(!this.xml && typeof XMLHttpRequest != "undefined")
this.xml = new XMLHttpRequest();
if (!this.xml){
this.failed = true;
}
var formData = new FormData();
/* Add the file */
formData.append("upload", file.files[0]);
xml.open("POST", "", true);
xml.setRequestHeader("Content-Type", "false");
xml.send(formData); /* Send to server */
xml.onreadystatechange = function () {
if (xml.readyState == 4 && xml.status == 200) {
alert(xml.statusText);
}
}
}
How to fetch the uploaded file object on struts2 server side?
It is going in server side class and I am trying to retrieve file by using request.getParameter(upload) but it is giving null.
function upload(form){
var fd = new FormData(form);
$.ajax({
url : "<url-value>", //this is the actionName
type: "POST",
data: fd,
processData: false,
contentType: false,
success: function(data){
},
error: function(xhr, status, error){
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
return false;
}
I think you missed to add the Action Link in the xml.open() method. Take a look at the MDN to see some examples.
How does your Action-class look like? Have you defined a File field named upload with getter/setters?
Please also check, that your browser supports the FormData element, see question.
I also would suggest you to use a library like jQuery to simplify the Javascript code.
Action
public class FileUpload extends ActionSupport {
File myFile;
public String execute() {
//do some preparations for the upload
return SUCCESS;
}
public String upload() {
//only here the myFile is filled with data
return SUCCESS;
}
public void setMyFile(File myFile) {
this.myFile = myFile;
}
public File getMyFile() {
return myFile;
}
}
struts.xml
<!-- init method to show the form -->
<action name="fileForm" class="...FileUpload">
<result name="success">fileupload.jsp</result>
</action>
<!-- upload method to upload the file -->
<action name="fileUpload" class="...FileUpload" method="upload">
<result name="success">fileupload.jsp</result>
</action>
JSP
<s:form enctype="multipart/form-data" method="post" name="fileinfo" action="fileUpload">
<s:file name="myFile"/>
</s:form>
<input type="submit" onClick="upload()" value="OK">
Javascript (taken from the MDN example above)
function upload() {
var fd = new FormData(document.querySelector("form"));
$.ajax({
url : "fileUpload", //this is the actionName
type: "POST",
data: fd,
processData: false,
contentType: false
});
return false; //to stop submitting the form
}
I have not tested this code, so please change it or add comments if something doesn't work.

mvc3 and evopdf - display "processing" message while the pdf is being generated

I am using MVC3 and evopdf (http://www.evopdf.com/) to create a pdf when user clicks on a print button.
I have the initial view that contains a form and print button and a 2nd view specifically designed for printing.
Clicking on the print button calls javascript to submit the form, which calls the print action.
What I would like to happen is that once the print button has been clicked, a "processing" message is displayed.
Once the pdf has been generated I would like the message to be removed.
This is the javascript (I have not included all of my javascript as there are parts that are not relevant)
$(document).ready(function () {
$(".btn").click(function () {
var delay = 10;
$("#AjaxDelay").val(delay);
$.blockUI();
$('#printForm').submit();
});
$('#printForm').submit(function () {
$.blockUI();
$.ajax({
url: this.action,
type: this.method,
success: function (data) {
$.unblockUI();
//I need to open the pdf in appropriate app, adobe pdf viewer or similar
},
failure:function(data) {
alert("error");
$.unblockUI();
}
});
return false;
});
});
The form
#using (Html.BeginForm("PrintView", "Index", new { format = "pdf/", id = Model.ID, AjaxDelay = Model.AjaxDelay }, FormMethod.Get, new { id="printForm" }))
{
#Html.HiddenFor(m=>m.AjaxDelay)
<button type="button" class="btn print" >Print</button>
}
IndexController
public ActionResult PrintView(int id)
{
var model = GetData(id);
return View(model);
}
This is my HttpHandler
public void ProcessRequest(HttpContext context)
{
if (!context.Request.IsAuthenticated) return;
ProducePDF(context, "pdf title", 20);
}
private void ProducePDF(HttpContext context, string title,int delay)
{
var pdfConverter = GetPdfConverter();
// set the license key
pdfConverter.LicenseKey = "licence key here";
pdfConverter.JavaScriptEnabled = true;
var pdfBytes = pdfConverter.GetPdfBytesFromUrl(context.Request.Url.ToString().Replace(".pdf/", ""));
// send the PDF document as a response to the browser for download
var response = HttpContext.Current.Response;
response.Clear();
response.AddHeader("Content-Type", "application/pdf");
response.AddHeader("Content-Disposition", String.Format("attachment; filename=" + title + ".pdf; size={0}", pdfBytes.Length));
response.BinaryWrite(pdfBytes);
response.End();
}
Thanks.
I found a solution that uses the jquery cookie plugin and appending a cookie to the response as described in this stackoverflow article.
Hide image using Javascript after controller action is complete MVC3
I did have to make a small change in that I had to specify the path when removing the cookie.

Fine Uploader- Server side code saves uploaded file but client displays 'Upload failed' message

I have an MVC2 application where I am trying to use the Fine-Uploader plugin. When I run through my code behind, it saves the file that I uploaded. However, what get's displayed back in the browser is Upload Failed. I'm not sure what I'm missing here. My code is below:
Code behind:
public void UploadFiles()
{
try
{
if (Request.Files.Count > 0)
{
foreach (string file in Request.Files)
{
HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase;
if (hpf.ContentLength == 0)
{
continue;
}
string filename = Path.GetFileName(hpf.FileName);
string path = Path.Combine(Server.MapPath(ConfigurationManager.AppSettings["AttachmentPath"]), filename);
hpf.SaveAs(path);
}
}
}
catch (Exception e)
{
//Do something
}
}
Master page:
<script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script>
<script src="<%=Url.Content("~/Scripts/jquery.fineuploader-3.5.0.js") %>" type="text/javascript"></script>
<script src="<%=Url.Content("~/Scripts/jquery.fineuploader-3.5.0.min.js") %>" type="text/javascript"></script>
Markup page:
<div id="manual-fine-uploader"></div>
<div id="triggerUpload" class="btn btn-primary" style="margin-top: 10px;">
<i class="icon-upload icon-white"></i> Upload now
</div>
<script type="text/javascript">
$(document).ready(function () {
var manualuploader = new qq.FineUploader({
element: $('#manual-fine-uploader')[0],
request: {
endpoint: 'Home/UploadFiles'
},
autoUpload: false,
text: {
uploadButton: '<i class="icon-plus icon-white"></i> Select Files'
}
});
$('#triggerUpload').click(function () {
manualuploader.uploadStoredFiles();
});enter code here
});
</script>
Fine Uploader expects a valid JSON response indicating whether the upload succeeded or not.
A successful upload response must have:
{ "success": true }
for Fine Uploader to know that it worked. You can add whatever else you want to your response, but without indicating 'success' Fine Uploader will think that the upload failed.
What I would do is add a return to your UploadFiles function. Somewhat like:
public UploadResult UploadFiles()
{
try
{
// ... save file and other things
}
catch (Exception ex)
{
// failsauce :(
return new UploadResult(false);
}
// success :)
return new UploadResult(true);
}
Where UploadResult is much like:
public class UploadResult
{
// This is important!
public const string ResponseContentType = "text/plain";
public FineUploaderResult(bool success)
{
_success = success;
}
public override void ExecuteResult(ControllerContext context)
{
// Here we create the JSON Response object,
// set the correct content-type, and finally
// it gets built with the correct success flag.
var response = context.HttpContext.Response;
response.ContentType = ResponseContentType;
response.Write(BuildResponse());
}
public string BuildResponse()
{
var response = new JObject();
response["success"] = _success;
// ... maybe set some other data in the response JSON
return response.ToString();
}
}
There is an example using ASP.NET MVC C# up on the server examples repository that may provide some assistance.
Also, on the development branch there is a server-side README which indicates exactly what constitutes a valid JSON response for Fine Uploader.

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.

Hide image using Javascript after controller action is complete MVC3

My application has been implemeted using MVC 3, .net.
I am trying to generate an excel file at the click of a button.
The call to the controller action is made using Ajax.
My main problem is: During the file generation i am trying to display an image on the screen to let the user know of the ingoing operation. I can very well display the image but i cannot hide it after the operation is completed. The codei am using is :
Javascript code:
$("input.DownloadExcelReport").click(function (e) {
e.preventDefault();
var parameter = -- code to fetch parameter value;
var outputViewUrl = (the url is created here);
showLoading(); -- This function displays the image
window.location.href = outputViewUrl;
});
Controller Action code:
public ActionResult DownExcelReportForAssortment(Guid parameter)
{
try
{
//the contents for the file generation are fetched here..
// Write contents to excel file
if (memoryStream != null)
{
var documentName = "Report.xls";
byte[] byteArrary = memoryStream.ToArray();
return File(byteArrary, "application/vnd.ms-excel", documentName);
}
}
catch (Exception ex)
{
LogManager.LogException(ex);
}
}
I do not return a Json result to the calling javascript method where i can write the code to hide the image.
I am returning a file which can be saved by the user and the action is completed.
Can somone please suggect/help me of how can i hide the image once the file generation operation is complete?
Appreciate the help...
You may checkout the following article and put this into action. So we start by defining a controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult DownExcelReportForAssortment(Guid parameter, string tokenId)
{
// Simulate some heavy work to fetch the report
Thread.Sleep(5000);
// we fake it
byte[] byteArray = System.IO.File.ReadAllBytes(#"c:\test.xls");
var cookie = new HttpCookie("fileDownloadToken", tokenId);
Response.AppendCookie(cookie);
return File(byteArray, "application/vnd.ms-excel", "report.xls");
}
}
and in the view:
#Html.ActionLink(
"download report",
"DownExcelReportForAssortment",
"Home",
new { parameter = Guid.NewGuid(), tokenId = "__token__" },
new { #class = "download" }
)
Now the last step is to include the jquery.cookie plugin:
<script type="text/javascript" src="#Url.Content("~/scripts/jquery.cookie.js")"></script>
and write a script to subscribe to the click event of the anchor and track the download progress:
$(function () {
var fileDownloadCheckTimer;
$('.download').click(function () {
var token = new Date().getTime();
$(this).attr('href', function () {
return this.href.replace('__token__', token);
});
// Show the download spinner
$('body').append('<span id="progress">Downloading ...</span>');
// Start polling for the cookie
fileDownloadCheckTimer = window.setInterval(function () {
var cookieValue = $.cookie('fileDownloadToken');
if (cookieValue == token) {
window.clearInterval(fileDownloadCheckTimer);
$.cookie('fileDownloadToken', null);
// Hide the download spinner
$('#progress').remove();
}
}, 1000);
});
});

Resources