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;
Related
Trying to upload a png file using S3-for-Google-Apps-Script library to S3 bucket:
// get the image blob
const imgBlob = UrlFetchApp.fetch('imageUrl').getBlob();
// init S3 instance
const s3 = S3.getInstance(awsAccessKeyId, awsSecretKey);
// upload the image to S3 bucket
s3.putObject(bucketName, 'test.png', imgBlob, { logRequests:true });
The file is uploading to S3 but not in a perfect way! It looks like this:
If I download the image and open getting the error:
"It may be damaged or use a file format that Preview doesn’t recognize."
So, how can I upload a .png file to amazon S3 bucket?
I can correctly upload the image when 'base64' is used to s3.putObject():
const base64 = Utilities.base64Encode(imgBlob.getBytes());
s3.putObject(bucketName, 'test.png', base64, { logRequests:true });
// go to S3 and clicking on the link I can see the base64 string
But this is uploading as String e.g. when I go S3 & click on test.png I see something like this: "iVBORw0KGgoAAAANSUhEUgAAAgAAAAI ... II=", but I want to see the actual image, not a String.
I believe your situation and goal as follows.
In your situation, the base64 data of the image can be uploaded. But, the uploaded data is not the image. It's the string data.
In your goal, you want to upload the image file of the publicly shared image using the image URL.
For this, how about this answer?
Issue and workaround:
When I saw the script of "S3-for-Google-Apps-Script", it seems that the URL cannot be directly used for s3.putObject(). And, the inputted blob is converted to the string type using getDataAsString(). I think that this is the reason of your issue.
In this answer, I would like to propose to modify the GAS library of "S3-for-Google-Apps-Script" for using the byte array to payload.
Usage:
At first, please copy the GAS project of S3-for-Google-Apps-Script, and please modify this as follows.
Modified script:
About S3.prototype.putObject in the file of S3.gs, please modify as follows.
From:
request.setContent(object.getDataAsString());
To:
request.setContent(object.getBytes());
And, about S3Request.prototype.setContent in the file of S3Request.gs, please modify as follows.
From:
if (typeof content != 'string') throw 'content must be passed as a string'
To:
// if (typeof content != 'string') throw 'content must be passed as a string'
And, about S3Request.prototype.getContentMd5_ in the file of S3Request.gs, please modify as follows.
From:
return Utilities.base64Encode(Utilities.computeDigest(Utilities.DigestAlgorithm.MD5, this.content, Utilities.Charset.UTF_8));
To:
return Utilities.base64Encode(Utilities.computeDigest(Utilities.DigestAlgorithm.MD5, this.content));
Sample script:
And, for above modified script, please test the following script.
const imageUrl = "###"; // Please set the image URL.
const s3 = S3.getInstance(awsAccessKeyId, awsSecretKey); // Please set them.
const imageBlob = UrlFetchApp.fetch(imageUrl).getBlob();
s3.putObject(bucketName, 'test.png', imageBlob, { logRequests:true });
By this, your token can be created by the modified library and use it.
When I checked this official document, I thought that the byte array might be able to be used.
References:
PutObject
S3-for-Google-Apps-Script
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
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();
}
I'm new to MVC and I'm stuck with a problem I need to display an image which is stored in database as byte in my MVC 4 application I know how to produce the image from the byte but I dont know how to display it in the App. how can I solve this
If you want to display the image directly from the db, you need a controller that delivers the image and call that controller in the view. This posts shows how to do it:
Display image from database in _layout in mvc4
Cheers,
Rob
If you have the FileData as a byte[] and the mime type as a string, then try this controller method:
public FileContentResult Get(Guid fileId)
{
var file = _fileService.GetFile(fileId);
if (file != null)
{
return File(file.FileData, file.MimeType);
}
else
{
// Return 1x1px transparent png (67 bytes) - This is a clever trick of mine to serve an empty image without reading it from the disk. You may not want to do this!
return File(Convert.FromBase64String("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAACklEQVR4nGMAAQAABQABDQottAAAAABJRU5ErkJggg=="), "image/png");
}
}
Then in your view you need the URL to the image, which is obtained by doing this:
<img src="#Url.Action("Get", new {fileId = item.ID})" />
I'm building a Win8/WinJS app that loads pictures from the local pictures library. Everything is generally working fine for loading valid images and displaying them in a list view.
Now I need to detect corrupt images and disable parts of the app for those images.
For example, open a text file and enter some text in it. Save the file as .jpg, which is obviously not going to be a valid jpg image. My app still loads the file because of the .jpg name, but now I need to disable certain parts of the app because the image is corrupt.
Is there a way I can check to see if a given image that I've loaded is a valid image file? To check if it's corrupt or not?
I'm using standard WinRT / WinJS objects like StorageFile, Windows.Storage.Search related objects, etc, to load up my image list based on searches for file types.
I don't need to filter out corrupt images from the search results. I just need to be able to tell if an image is corrupt after someone selects it in a ListView.
One possible solution would be to check the image's width and height properties to determine whether it is valid or not.
Yeah, the contentType property will return whatever the file extension is. The best way I can find it to look at the image properties:
file.properties.getImagePropertiesAsync()
.done(function(imageProps) {
if(imageProps.width === 0 && imageProps.height === 0) {
// I'm probably? likely? invalid.
});
where SelectImagePlaceholder is an Image Control.. =)
StorageFile file;
using (IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read))
{
try
{
// Set the image source to the selected bitmap
BitmapImage bitmapImage = new BitmapImage();
await bitmapImage.SetSourceAsync(fileStream);
SelectImagePlaceholder.Source = bitmapImage;
//SelectImagePlaceholder.HorizontalAlignment = HorizontalAlignment.Center;
//SelectImagePlaceholder.Stretch = Stretch.None;
this.SelectImagePlaceholder.DataContext = file;
_curMedia = file;
}
catch (Exception ex)
{
//code Handle the corrupted or invalid image
}
}