GWT Image Upload empty content - file-upload

I am trying to implement GWT image upload functionality. I have made the required code change but for some reason upload is not happening. At the server side the image is not being received. So I checked at the client side (browser) the request header and content and then I found that Content-Length: 44 (just 44). Then I realized that the image is not being sent to server on from submission. Please check the below GWT code.
VerticalPanel vp = new VerticalPanel();
vp.add(CommonFormLayoutUtil.createLabel("Upload"));
final FormPanel form = new FormPanel();
form.setAction("CGIImageUpload");
// set form to use the POST method, and multipart MIME encoding.
form.setEncoding(FormPanel.ENCODING_MULTIPART);
form.setMethod(FormPanel.METHOD_POST);
final FileUpload fileUpload = new FileUpload();
Button uploadButton = new Button("Upload");
uploadButton.addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
//get the filename to be uploaded
String filename = fileUpload.getFilename();
if (filename.length() == 0) {
showError("No File Specified!", null);
} else {
//submit the form
form.submit();
}
}
});
vp.add(fileUpload);
vp.add(uploadButton);
form.addSubmitCompleteHandler(new FormPanel.SubmitCompleteHandler() {
#Override
public void onSubmitComplete(SubmitCompleteEvent event) {
// When the form submission is successfully completed, this
//event is fired. Assuming the service returned a response
//of type text/html, we can get the result text here
showError(event.getResults(), null);
}
});
form.add(vp);
Am i missing anything here? Please suggest.
Thanks.

FormPanel states the following:
"This panel can be used to achieve interoperability with servers that accept traditional HTML form encoding. The following widgets (those that implement com.google.gwt.user.client.ui.HasName) will be submitted to the server if they are contained within this panel" (emphasis mine)
You need to set the name of the FileUpload widget otherwise it will not be submitted by the FormPanel.
fileUpload.setName("someName");
Try setting this and it should work

Related

Blob Storage Images - Azure

I have some problems with images that I upload through my web api to a public container in my blob storage. The problem is that i need the image i uploaded through my api have to be browseable, i mean when put the public link in a browser you can see the image in the browser, but the actual behavior is that when i put the link the image make a download of the image and doesnt show me nothing in the browser But when i Upload the image through the azure portal i can see the image as I want.... I have my container public and i dont know what else to do.... my code to upload a image is this:
private readonly CloudBlobContainer blobContainer;
public UploadBlobController()
{
var storageConnectionString = ConfigurationManager.AppSettings["StorageConnectionString"];
var storageAccount = CloudStorageAccount.Parse(storageConnectionString);
var blobClient = storageAccount.CreateCloudBlobClient();
blobContainer = blobClient.GetContainerReference("messagesthredimages");
blobContainer.CreateIfNotExists();
blobContainer.SetPermissions(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });
}
[HttpPost]
[Route("UploadImagetoBlob")]
public async Task<IHttpActionResult> UploadImagetoBlob()//string imagePath
{
try
{
var image = WebImage.GetImageFromRequest();
var imageBytes = image.GetBytes();
var blockBlob = blobContainer.GetBlockBlobReference(image.FileName);
blockBlob.Properties.ContentType = "messagesthreadimages/" + image.ImageFormat;
await blockBlob.UploadFromByteArrayAsync(imageBytes, 0, imageBytes.Length);
return Ok(blockBlob.Uri.ToString());
}
catch (Exception)
{
return BadRequest();
}
}
Examples, I hope somebody can help me with this.
What I Want => Correct
What I dont Want => Incorrect
I have faced the same issue before. Browsers download a file when they do not know the format (file type). If you monitor the files with the desktop app (no sure where this option is in the portal), you will find the file types.
These file types are set based on the blockBlob.Properties.ContentType you are setting. You need to inspect and check what exactly image.ImageFormat returns. The browser would only display the image if the this value is set to something like "image/jpeg". However since you are using "messagesthreadimages/" + image.ImageFormat, it might be setting something like "messagesthreadimages/image/jpeg".
As Neville said, you have some misunderstand when you call SetProperties method like blockBlob.Properties.ContentType.
Content-Type indicates the media type of the message content.
The image content type allows standardized image files to be included in messages. For more detail,you could refer to this link.
image/g3fax [RFC1494]
image/gif [RFC1521]
image/ief (Image Exchange Format) [RFC1314]
image/jpeg [RFC1521]
image/tiff (Tag Image File Format) [RFC2301]
I read this article and it seems that you would customize the ContentType of image.
So, you could change code as below:
blockBlob.Properties.ContentType = "image/" + image.ImageFormat;

Rotativa pdf doesn't work when published to Azure Server

I have a web app with Asp.net MVC 5 and I used Rotativa for the pdf.
Rotativa doesn't work when published to Azure Server but it works on my local computer.
It is giving bellow error
500 - THE REQUEST TIMED OUT.
The web server failed to respond within the specified time.
Bellow is my code.
public ActionResult DoPdf(int id)
{
return new ActionAsPdf("PrintMyPdf", new { id = id }) { FileName = string.Format("Demo_{0}.pdf", id) };
}
Here is a list of frameworks and scenarios that have been found to be not be usable due to the restrictions byAzure Web App sandbox
https://github.com/projectkudu/kudu/wiki/Azure-Web-App-sandbox#unsupported-frameworks
Please suggest how can I do PDF of my HTML view in MVC 5?
I suggest you to use the HTML to PDF for Azure Websites from EvoPdf. You have full control over the HTML to PDF Azure cloud service because you are the owner of the service and you don't have to worry about thing like the security of the data you send for conversion. The code you are using in your website looks like below:
protected void convertToPdfButton_Click(object sender, EventArgs e)
{
// Get the server IP and port
String serverIP = textBoxServerIP.Text;
uint serverPort = uint.Parse(textBoxServerPort.Text);
// Create a HTML to PDF converter object with default settings
HtmlToPdfConverter htmlToPdfConverter = new HtmlToPdfConverter(serverIP, serverPort);
// Set optional service password
if (textBoxServicePassword.Text.Length > 0)
htmlToPdfConverter.ServicePassword = textBoxServicePassword.Text;
// Set HTML Viewer width in pixels which is the equivalent in converter of the browser window width
htmlToPdfConverter.HtmlViewerWidth = int.Parse(htmlViewerWidthTextBox.Text);
// Set HTML viewer height in pixels to convert the top part of a HTML page
// Leave it not set to convert the entire HTML
if (htmlViewerHeightTextBox.Text.Length > 0)
htmlToPdfConverter.HtmlViewerHeight = int.Parse(htmlViewerHeightTextBox.Text);
// Set PDF page size which can be a predefined size like A4 or a custom size in points
// Leave it not set to have a default A4 PDF page
htmlToPdfConverter.PdfDocumentOptions.PdfPageSize = SelectedPdfPageSize();
// Set PDF page orientation to Portrait or Landscape
// Leave it not set to have a default Portrait orientation for PDF page
htmlToPdfConverter.PdfDocumentOptions.PdfPageOrientation = SelectedPdfPageOrientation();
// Set the maximum time in seconds to wait for HTML page to be loaded
// Leave it not set for a default 60 seconds maximum wait time
htmlToPdfConverter.NavigationTimeout = int.Parse(navigationTimeoutTextBox.Text);
// Set an adddional delay in seconds to wait for JavaScript or AJAX calls after page load completed
// Set this property to 0 if you don't need to wait for such asynchcronous operations to finish
if (conversionDelayTextBox.Text.Length > 0)
htmlToPdfConverter.ConversionDelay = int.Parse(conversionDelayTextBox.Text);
// The buffer to receive the generated PDF document
byte[] outPdfBuffer = null;
if (convertUrlRadioButton.Checked)
{
string url = urlTextBox.Text;
// Convert the HTML page given by an URL to a PDF document in a memory buffer
outPdfBuffer = htmlToPdfConverter.ConvertUrl(url);
}
else
{
string htmlString = htmlStringTextBox.Text;
string baseUrl = baseUrlTextBox.Text;
// Convert a HTML string with a base URL to a PDF document in a memory buffer
outPdfBuffer = htmlToPdfConverter.ConvertHtml(htmlString, baseUrl);
}
// Send the PDF as response to browser
// Set response content type
Response.AddHeader("Content-Type", "application/pdf");
// Instruct the browser to open the PDF file as an attachment or inline
Response.AddHeader("Content-Disposition", String.Format("{0}; filename=Getting_Started.pdf; size={1}",
openInlineCheckBox.Checked ? "inline" : "attachment", outPdfBuffer.Length.ToString()));
// Write the PDF document buffer to HTTP response
Response.BinaryWrite(outPdfBuffer);
// End the HTTP response and stop the current page processing
Response.End();
}

How to configure ZK form to show browser cache data?

I am new to ZK framework. As per my requirement, I need to convert JSP-Servlet based application into ZK framework. One requirement is I need to show previously filled data [stored in browser cache] in forms input boxes when user click in that input box or type similar characters.
This was the default behavior in the JSP-Servlet application or any other HTML based GUI. But by default ZK form does not show previously filled data. I tried some googling to find its solution but could not found any. Please provide me the solution for that.
Thanks in advance :)
You can use cookies for that.
Here is a link to the documentation of cookies for zk.
Code provided in the link :
public void onCookie(){
try {
//add cookie
HttpServletResponse response = (HttpServletResponse)Executions.getCurrent().getNativeResponse();
Cookie userCookie = new Cookie("user", "xxx123");
response.addCookie(userCookie);
//get cookie
Cookie [] cookies = ((HttpServletRequest)Executions.getCurrent().getNativeRequest()).getCookies();
System.out.println(cookies[0].getName());
} catch (Exception e) {
e.printStackTrace();
}
}

Window phone - How to redirect to page xaml form web browser control?

I have two page xaml contain web browser control to display html string.For example,
page1.xaml : Contain webbrowser control (will display html string to web browser control)
page2.xaml : Contain webbrowser control
Question is : When user click a tag hyperlink in page1.xaml and how to redirect to page2.xaml
you can simply use the java script function that call the your native C# function by this you can call the native function from web browser and redirect the page.
so please create the one html file inside the html use the Javascript function that call the native function or notify from there.
You need to inject Javascript in the HTML that will enumerate all a tags and wire up an onclick event. That event will call window.external.Notify which will in turn raise the ScriptNotify event of the WebBrowser, with the URL as a parameter.
Here is the code:
// Constructor
public MainPage()
{
InitializeComponent();
browser.IsScriptEnabled = true;
browser.ScriptNotify += browser_ScriptNotify;
browser.Loaded += browser_Loaded;
}
void browser_Loaded(object sender, RoutedEventArgs e)
{
// Sample HTML code
string html = #"<html><head></head><body><a href='http://www.google.fr'>Google</a></body></html>";
// Script that will call raise the ScriptNotify via window.external.Notify
string notifyJS = #"<script type='text/javascript' language='javascript'>
window.onload = function() {
var links = document.getElementsByTagName('a');
for(var i=0;i<links.length;i++) {
links[i].onclick = function() {
window.external.Notify(this.href);
}
}
}
</script>";
// Inject the Javascript into the head section of the HTML document
html = html.Replace("<head>", string.Format("<head>{0}{1}", Environment.NewLine, notifyJS));
browser.NavigateToString(html);
}
void browser_ScriptNotify(object sender, NotifyEventArgs e)
{
if (!string.IsNullOrEmpty(e.Value))
{
// Navigate to Page2.xaml
NavigationService.Navigate(new Uri("/Page2.xaml", UriKind.Relative));
}
}
The solution that you are looking for is deeplinking your app to listen to custom URL protocols.
First setup your solution to listen to custom URLs. Follow the URI association section in this MSDN document. http://msdn.microsoft.com/en-us/library/windowsphone/develop/jj206987(v=vs.105).aspx#BKMK_URIassociations
Next in your web browser when you display a link make sure it is an absolute URL starting with your own protocol and NOT http or https.
So, your final url in the web browser must contain something like that: my_protocol://abc.xaml
In the AssociationURIMapper class, you catch such URLs and navigate to the desired XAML page.
This solution will not only enable your app to open from a web browser but also from other applications on windows phone!

Windows 8 Tile does not update

The following code worked when I followed the tutorial using a new project:
http://www.amazedsaint.com/2011/09/hellotiles-simple-c-xaml-application.html
However, I am unable to get the application's tile to update when I plug-in the same code to my real project.
I have rebuilt the package.
I have uninstalled and redeployed the app.
I have updated the wide logo image file.
I have verified that the same code works when creating a new project.
I have verified the app manifest as suggested by the linked tutorial.
How does this work fine in one solution but not the other?
public MainPage()
{
this.InitializeComponent();
ClearTileNotification();
SendTileTextNotification("Why isn't this working!");
}
void ClearTileNotification()
{
// the same TileUpdateManager can be used to clear the tile since
// tile notifications are being sent to the application's default tile
TileUpdateManager.CreateTileUpdaterForApplication().Clear();
}
void SendTileTextNotification(string text)
{
// Get a filled in version of the template by using getTemplateContent
var tileXml = TileUpdateManager.GetTemplateContent(TileTemplateType.TileWideText03);
// You will need to look at the template documentation to know how many text fields a particular template has
// get the text attributes for this template and fill them in
var tileAttributes = tileXml.GetElementsByTagName("text");
tileAttributes[0].AppendChild(tileXml.CreateTextNode(text));
// create the notification from the XML
var tileNotification = new TileNotification(tileXml);
// send the notification to the app's default tile
TileUpdateManager.CreateTileUpdaterForApplication().Update(tileNotification);
}