cq5 determine file content type or media type or mimetype - aem

I have following code to save an asset in a servler service
ResourceResolver resourceResolver = this.resolverFactory.getAdministrativeResourceResolver(null);
AssetManager assetMgr = (AssetManager)resourceResolver.adaptTo((Class)AssetManager.class);
String newFile = "/content/dam/travel/" + fileName;
assetMgr.createAsset(newFile, is, "image/jpeg", true);
The following line creates the asset with specified mimetype
assetMgr.createAsset(newFile, is, "image/jpeg", true);
I would like to determine the coming file content type based on stream rather than name.
Thank you,
Sri

Related

MultipartFormDataContent encode single quote in .NET Standard

I have file which name contains single quote like Test'Quote.html
in order to upload file to server, I'm using HttpClient and MultipartFormDataContent like:
using (var formContent = new MultipartFormDataContent($"{new string('-', 10)}-{DateTime.Now.Ticks}"))
{
foreach (var file in files)
{
var fileContent = new StreamContent(file.Stream);
fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse(file.ContentType);
formContent.Add(fileContent, file.Name, file.Filename);
}
await client.PostAsync(address, formContent)
}
I check formContent and I see:
And I cannot upload file to server because it says that filename is invalid, seems that last filename is taken in consideration instead of first one.
How to disable or avoid encoding such name ?

How to get type of file?

I'm trying to find a package which would recognise file type. For example
final path = "/some/path/to/file/file.jpg";
should be recognised as image or
final path = "/some/path/to/file/file.doc";
should be recognised as document
You can make use of the mime package from the Dart team to extract the MIME types from file names:
import 'package:mime/mime.dart';
final mimeType = lookupMimeType('/some/path/to/file/file.jpg'); // 'image/jpeg'
Helper functions
If you want to know whether a file path represents an image, you can create a function like this:
import 'package:mime/mime.dart';
bool isImage(String path) {
final mimeType = lookupMimeType(path);
return mimeType.startsWith('image/');
}
Likewise, if you want to know if a path represents a document, you can write a function like this:
import 'package:mime/mime.dart';
bool isDocument(String path) {
final mimeType = lookupMimeType(path);
return mimeType == 'application/msword';
}
You can find lists of MIME types at IANA or look at the extension map in the mime package.
From file headers
With the mime package, you can even check against header bytes of a file:
final mimeType = lookupMimeType('image_without_extension', headerBytes: [0xFF, 0xD8]); // jpeg
There is no need of any extension. You can try below code snippet.
String getFileExtension(String fileName) {
return "." + fileName.split('.').last;
}
If think you should take a look to path package, specially to extension method.
You can get file format without adding one more package to pubspec.yaml ;)
context.extension('foo.bar.dart.js', 2); // -> '.dart.js
context.extension('foo.bar.dart.js', 3); // -> '.bar.dart.js'
context.extension('foo.bar.dart.js', 10); // -> '.bar.dart.js'
context.extension('path/to/foo.bar.dart.js', 2); // -> '.dart.js'

Getting filename that was used on setGraphic()

I am currently working on a puzzle type of app on javaFX. I created a 2d array of buttons that I used setGraphic to insert the pictures. I am wondering if there is a way to retrieve the filename that I used on setGraphic so I can compare to pictures together. I know there is a getGraphic method but that returns random numbers.
setGraphic takes a Node, not a Image object; I assume you use ImageViews as graphics.
There is no way to retrieve the file name from an Image object since you need not pass a url to the Image constructor but are also allowed to pass a InputStream. InputStream does not provide any information about it's source and Image also doesn't.
To get the file path from a image you need to store the information yourself, e.g.:
private final Map<Image, String> imageFileNames = new IdentityHashMap<>();
public Image loadImage(String filename) throws MalformedURLException {
File file = new File(filename);
Image image = new Image(file.toURI().toURL().toExternalForm());
imageFileNames.put(image, filename);
return image;
}
public String getImageFileName(Image image) {
return imageFileNames.get(image);
}
With a node containing a ImageView as a graphic, you could do something like this:
ImageView view = (ImageView) node.getGraphic();
Image img = view.getImage();
String fileName = getImageFieldName(img);
Possibly adding null checks, if the graphic and/or the image can be null.
You could also the data in the node's userData or properties if you like:
Storing
File file = new File(filename);
ImageView imageView = new ImageView(file.toURI().toURL().toExternalForm());
imageView.setUserData(filename);
Retrieving
String filename = (String) node.getGraphic().getUserData();

Eclipse - Convert IPath to URL

How can I convert an IPath to a URL. In my case, I want to convert the output location of a Java project to a URL, so that I can load classes from there with the URLClassLoader. My code looks like this:
javaProject.getProject().build(IncrementalProjectBuilder.FULL_BUILD, null);
URL url = new File( javaProject.getOutputLocation().toFile().getAbsolutePath() ).toURI().toURL();
URL[] urls = new URL[] { url };
URLClassLoader classLoader = new URLClassLoader(urls);
Class<?> c = classLoader.loadClass(fully-qualified-class-name);
The problem is that the URL is only a relative one, i.e. its string representation is file:/C:/com.florianingerl.regexfindandreplace.matchevaluators/bin but it should be something like file:/C:/Users/Hermann/runtime-EclipseApplication/com.florianingerl.regexfindandreplace.matchevaluators/bin
The URLClassLoader can't find the classes obviously.
Any help is appreciated.
You can use something like:
IPath path = javaProject.getOutputLocation();
IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(path);
URI uri = file.getLocationURI();
URL url = uri.toURL();

ExcelSoftArtisans - Bug on Save method with open Stream - Cannot accessed closed file

I have the following issue:
I’m doing an export of an ASP.Net GridView directly to an excel file.
I’m setting an image as a header in this method:
private static void insertPageHeaderFooter(ExcelInterfaceSoftArtisans excel,DateTime generatedDateTime)
{
StringBuilder builderFooterLeft = new StringBuilder();
builderFooterLeft.Append("&08Comfone AG Tel: +41 31 341 10 10");
builderFooterLeft.Append("\r");
builderFooterLeft.Append("&08Nussbaumstrasse 25 Fax: +41 31 341 10 11");
builderFooterLeft.Append("\r");
builderFooterLeft.Append("&08CH-3000 Bern 22 www.comfone.com");
StringBuilder builderFooterRight = new StringBuilder();
String sDateTime = generatedDateTime.ToString(CultureInfoHandler.ShortDateShortTimeFormat);
builderFooterRight.Append("&08&F");
builderFooterRight.Append("\r");
builderFooterRight.Append(string.Format("&08 {0}", sDateTime));
builderFooterRight.Append("\r"); //new line
builderFooterRight.Append("&08Page &P of &N");
excel.SetHeader("&G", 0.6, HeaderFooterSection.Section.Left, false);
excel.SetFooter(builderFooterLeft.ToString(), HeaderFooterSection.Section.Left, false);
excel.SetFooter(builderFooterRight.ToString(), HeaderFooterSection.Section.Right, false);
}
protected void SetHeader(string sText, double dImageSizeFactor, HeaderFooterSection.Section section, Worksheet sheet)
{
string headerAbsolutePath = HttpContext.Current.Server.MapPath("~/Resources/Mandates/CHECF.png");
Stream imageStream = new FileStream(headerAbsolutePath, FileMode.Open, FileAccess.Read);
Size imageSize = Image.FromStream(imageStream).Size;
imageStream = new FileStream(headerAbsolutePath, FileMode.Open, FileAccess.Read);
HeaderFooterSection header = sheet.PageSetup.GetHeader(section);
header.SetContent(sText, imageStream);
header.SetContent(sText);
header.GetPicture().Height = (int)(imageSize.Height * dImageSizeFactor);
header.GetPicture().Width = (int)(imageSize.Width * dImageSizeFactor);
imageStream.Close();
}
As you can see on the last line, I close the Stream.
Now, I want to save my excel file this way:
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearHeaders();
excel.SaveWorkbook(sFileName, HttpContext.Current.Response, false);
/// <summary>
/// Saves the current Workbook under the given filename
/// </summary>
/// <param name="filename"></param>
/// <param name="response"></param>
/// <param name="openInBrowser"></param>
public void SaveWorkbook(string filename, HttpResponse response, bool openInBrowser)
{
if (book != null)
{
application.Save(book, response, filename, openInBrowser);
}
}
but when I close the stream in the SetHeader method, I get the following error:
Error Message: Cannot access a closed file.
Stack Trace: at System.IO.__Error.FileNotOpen()
at System.IO.FileStream.Seek(Int64 offset, SeekOrigin origin)
and when I don’t close the stream in the SetHeader method, the file is correctly saved.
Are you aware of this bug? How is it possible that I need to have an open stream in order to save an excel file? What can I do to fix that?
I’m attaching you the whole classes I’m using, so you can identify the problem better.
Thanks for your quick answer and solution on this problem.
[Disclaimer: I am the product owner of OfficeWriter]
This issue has been confirmed as a bug and has been submitted to the OfficeWriter development team.
In the meantime, I would recommend Sam's suggested workaround of using the overload that takes the image's file path instead of the image stream.
Here is a generic code snippet for how to insert an image into the header of an Excel file using the file path overload of HeaderFooterSection.SetContent():
//Open the workbook and get a handle on the worksheet that will contain the
//image in the header
ExcelApplication xla = new ExcelApplication();
Workbook wb = xla.Open(Page.MapPath("\\template.xlsx"));
Worksheet ws = wb.Worksheets["Sheet1"];
//Set the header
HeaderFooterSection header = ws.PageSetup.GetHeader(HeaderFooterSection.Section.Left);
header.SetContent("&G", Page.MapPath("\\images\\image1.png"));
Please see our documentation for additional reference on the SetContent() overloads and using ExcelWriter to format headers and footers in workbooks.
This issue has been addressed in the recent 8.5.1 release of OfficeWriter. See the change log.