How to open remote path pdf in webview xamarin.forms - xamarin

I am working in xamarin.forms. I got HTML content as josn Response.
<!-- THEME DEBUG --> <!-- CALL: theme('node') --> <!-- FILE NAME SUGGESTIONS: * node--253.tpl.php * node--article.tpl.php x node.tpl.php -->
<!-- BEGIN OUTPUT from 'sites/all/themes/maharastracmonew/templates/node.tpl.php' -->
<div id="node-253" class="node node-article clearfix" about="/maharastracmo/en/magazines" typeof="sioc:Item foaf:Document">
<h2> Magazine Gallery </h2>
<span property="dc:title" content="Magazine Gallery" class="rdf-meta element-hidden"></span>
<span property="sioc:num_replies" content="0" datatype="xsd:integer" class="rdf-meta element-hidden"></span>
<div class="field field-name-body field-type-text-with-summary field-label-hidden">
<div class="field-items">
<div class="field-item even" property="content:encoded">
<div class="innerContent">
<div class="pdfBlock">
<div class="pdfIconBox">
<a href="http://14.141.36.212/maharastracmo/sites/all/themes/maharastracmonew/pdf/MA-June15-binder-6.pdf" target="_blank">
<img alt="" src="http://14.141.36.212/maharastracmo/sites/all/themes/maharastracmonew/images/book-icon.png" />
</a>
<h5>Maharashtra Ahead</h5> <span class="bookDate">June 2015</span>
</div>
</div>
</div>
</div>
</div>
</div>
</div> <!-- END OUTPUT from 'sites/all/themes/maharastracmonew/templates/node.tpl.php' -->
In this content there is one image and on when user click on image .pdf is open in new browser.
I create html and display that html in WebView but on image click pdf file is doesn't open. pdf file is comes from remote device. (Server).
Second Try :
As a second option I have taken webview and simply put pdf remote path as source property but blank page is open. How can I solve this problem?
Third Try :
I simply use one button and on button click event pdf path is open in another browser. but doesn't open instead pdf file is directly download.
protected async void OnClicked(object sender, EventArgs e)
{
var uri = new Uri("http://14.141.36.212/maharastracmo/sites/all/themes/maharastracmonew/pdf/MA-June15-binder-6.pdf");
Device.OpenUri(uri);
}

Need to use Xamarin Dependency Service. Here is how I did it.
First Define an interface:
namespace Mobile.DependencyService
{
/// <summary>
///
/// </summary>
public interface IDownload
{
/// <summary>
///
/// </summary>
/// <param name="name"></param>
/// <param name="bytes"></param>
/// <param name="fullPathToSavedFile"></param>
void Save(string name, byte[] bytes, out string fullPathToSavedFile);
}
}
Inside your click event: var uri = your link to the pdf;
var uri = repository.GetResumeUri(model);
if (Device.OS == TargetPlatform.Android)
{
using (var clientHandler = new System.Net.Http.HttpClientHandler())
{
using (var httpClient = new System.Net.Http.HttpClient(clientHandler))
{
httpClient.BaseAddress = uri;
byte[] bytes = await httpClient.GetByteArrayAsync(uri);
var service = Xamarin.Forms.DependencyService.Get<Mobile.DependencyService.IDownload>();
string fullPathToSavedFile;
service.Save(
String.Format("{0}.pdf", System.Guid.NewGuid().ToString("N")), //String.Format("{0} Resume.pdf", model.Type),
bytes,
out fullPathToSavedFile
);
uri = new Uri(String.Format("file://{0}", fullPathToSavedFile));
}
}
}
Device.OpenUri(uri);
In iOS:
[assembly: Xamarin.Forms.Dependency(typeof(Mobile.iOS.DependencyService.Download))]
namespace Mobile.iOS.DependencyService
{
public class Download : IDownload
{
public void Save(string name, byte[] bytes, out string fullPathToSavedFile)
{
fullPathToSavedFile = String.Empty;
try
{
fullPathToSavedFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), name);
File.WriteAllBytes(fullPathToSavedFile, bytes);
}
catch (Exception ex)
{
var ex1 = ex;
}
}
}
}
For Android:
[assembly: Xamarin.Forms.Dependency(typeof(Mobile.Droid.DependencyService.Download))]
namespace Mobile.Droid.DependencyService
{
public class Download : IDownload
{
public void Save(string name, byte[] bytes, out string fullPathToSavedFile)
{
fullPathToSavedFile = String.Empty;
// https://developer.xamarin.com/api/type/System.Environment+SpecialFolder/
// http://developer.android.com/guide/topics/data/data-storage.html
try
{
//var path = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), name);
using(var directory = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads))
{
if (null != directory)
{
var state = Android.OS.Environment.GetExternalStorageState(directory);
if (String.Compare(state, Android.OS.Environment.MediaMounted,true)==0)
{
fullPathToSavedFile = Path.Combine(directory.AbsolutePath, name);
File.WriteAllBytes(fullPathToSavedFile, bytes);
//File.WriteAllBytes(Path.Combine(directory.AbsolutePath, name), bytes);
}
}
}
}
catch(Exception ex)
{
var ex1 = ex;
}
}
}
}

Related

Multiple photos upload via Cloudinary.DotNet

I have configured my CloudinaryService to upload JUST ONE photo on my cloud on cloudinary. But i have really great troubles with configuring this to make it work on multiple uploads. Please help me, here is my code for single upload:
public async Task<string> UploadPictureAsync(IFormFile pictureFile, string fileName)
{
byte[] destinationData;
using (var ms = new MemoryStream())
{
await pictureFile.CopyToAsync(ms);
destinationData = ms.ToArray();
}
UploadResult uploadResult = null;
using (var ms = new MemoryStream(destinationData))
{
ImageUploadParams uploadParams = new ImageUploadParams
{
Folder = "cars",
File = new FileDescription(fileName, ms),
PublicId = "audizone"
};
uploadResult = this.cloudinaryUtility.Upload(uploadParams);
}
return uploadResult?.SecureUri.AbsoluteUri;
}
}
}
I change IFormFile pictureFile to List<IFormFile> pictureFiles, going on with foreach (file in pictureFiles)...the only thing this service is doing is just uploading 2 or 3 times the same picture(the first one of three or two)...just not uploading two or three different photos.
<form asp-action="Create" method="post" enctype="multipart/form-data">
<input type="file" multiple
class="form-control text-primary text-center"
id="picture"
name="picture"
placeholder="Picture..." />
<input type="submit" value="Submit" class="btn btn-dark" style="border-bottom-left-
radius:25%;border-bottom-right-radius:25%" />
</form>
I managed to successfully loop using this method:
public static void BulkUpload(List<string> filePaths, ResourceType resourceType = ResourceType.Image, string type = "upload")
{
var cloudinary = GetCloudinary(); // Initializing Cloudinary
foreach (var path in filePaths)
{
byte[] bytes = File.ReadAllBytes(path);
var streamed = "streamed";
using (MemoryStream memoryStream = new MemoryStream(bytes))
{
ImageUploadParams uploadParams = new ImageUploadParams()
{
File = new FileDescription(streamed, memoryStream)
};
ImageUploadResult uploadResult = cloudinary.Upload(uploadParams);
if (uploadResult.StatusCode == HttpStatusCode.OK)
Console.WriteLine("uploaded: " + uploadResult.PublicId);
else
Console.WriteLine("Failed: " + uploadResult.Error);
}
}
}

Can´t render upload images in Magnolia CMS

i have a content app in Magnolia CMS, now i need to redner a image of the class DamUploadFieldDefinition from a content app
jcr node
I have tried this in my .ftl:
<img src = "${cmsfn.link(news.jcrPhoto)}" />
But only return a path of the photo and can´t render my photo
Searching i found this solution but doesn´t render:
<img src="${damfn.getRendition(news.jcrPhoto, "myAssetVariante").link}" />
I was looking in another content app named "contacts" of MAgnolia, and they make it through a model class:
public class NewsModel<RD extends TemplateDefinition> extends AbstractSTKTemplateModel<TemplateDefinition> {
private Node news;
#Inject
public NewsModel(Node content, TemplateDefinition definition, RenderingModel<?> parent,
STKTemplatingFunctions stkFunctions, TemplatingFunctions templatingFunctions) {
super(content, definition, parent, stkFunctions, templatingFunctions);
System.out.println("Entramos en el constructor");
}
/**
* FIXME: should be done better (binaryHandling): SCRUM-525.
*/
public String getPhoto() {
System.out.println("BOB inicio en el getPhoto");
if (news == null) {
System.out.println("news == null");
return null;
}
Property binaryData = null;
try {
if (news.hasNode("photo")) {
System.out.println("Tenemos contenido");
Node binaryNode = news.getNode("photo");
binaryData = binaryNode.getProperty("jcr:data");
}
} catch (RepositoryException e) {
throw new RuntimeException(e);
}
if (binaryData != null) {
System.out.println("retornamos desde templatingFunctions");
return templatingFunctions.link(binaryData);
} else {
System.out.println("retornamos null");
return null;
}
}
public ContentMap getNews() {
System.out.println("Inicio getNews");
ContentMap cm = templatingFunctions.asContentMap(news);
System.out.println("ContentMap=\n"+cm);
return cm;
}
public void setNews(Node news) {
this.news = news;
}
#Override
public String execute() {
System.out.println("En el execute");
try {
NodeIterator ni = content.getNodes();
System.out.println("size:"+ni.getSize());
while(ni.hasNext()){
System.out.println(ni.toString());
Node n = ni.nextNode();
System.out.println(n.getIdentifier());
}
} catch (RepositoryException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//String id = PropertyUtil.getString(content, "news");
String id = "651c7140-b681-45b4-8814-ae26bfa0ba0d";
news = null;
System.out.println("id="+id);
if (StringUtils.isNotEmpty(id)) {
System.out.println("En el if del execute");
try {
news = new HTMLEscapingContentDecorator(true).wrapNode(NodeUtil.getNodeByIdentifier("news",id));
}
catch (RepositoryException e) {
System.out.println("Can't get uuid: '" + id + "' of contact.");
}
}
return super.execute();
}
}
And my FTL is:
[#assign news = model.news!]
7
[#if news?has_content]
8
[#assign hasPhoto = model.photo?has_content]
[/#if]
[#if contact?has_content]
9
[#if hasPhoto]
10
<dl class="media photo pos-2">
<dt><img src="${model.photo}"/></dt>
</dl>
[/#if]
[/#if]
When i put String id = PropertyUtil.getString(content, "news"); ID is null so don´t pass in if (StringUtils.isNotEmpty(id)) {
So i hardcode putting
String id = "651c7140-b681-45b4-8814-ae26bfa0ba0d";
and run all code but id doesn´t show the img
Result
Showing Google´s console i can see the image path:
/mgnl-prosegur-intra-webapp/01/photo
But even putting the src like Contacts content app with my image name, dont shows anything
<img src="/mgnl-prosegur-intra-webapp/demo-project/contacts/ldavinci/photo/vitruviano.jpeg" alt="">
Changed to should be:
<img src="/mgnl-prosegur-intra-webapp/demo-project/contacts/ldavinci/photo/vitruviano.jpeg" alt="">
But not function
Please
if image is in DAM (Assets app), try this:
<img src="${damfn.getAssetLink(news.jcrPhoto)}">

Server.MapPath check for folder and create

I'm uploading an image to a folder images. it's working fine.but what I actually want is to look for a folder name (I have the folder name) if not found create that folder and give it that name.how could that happen?
this is what I have done so far:
string ImageName = System.IO.Path.GetFileName(file.FileName);
string physicalPath = Server.MapPath("~/images/" + ImageName);
instead of images I should have folderName.
the complete view:
#{
ViewBag.Title = "Index";
}
#using (Html.BeginForm("FileUpload", "datum", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
<div>
category<br />
#Html.DropDownList("category", ViewBag.Roles as SelectList)
<br/>
description<br />
#Html.TextBox("description") <br />
Image<br />
<input type="File" name="file" id="file" value="Choose File" />
<input type="submit" value="Upload" class="submit" />
</div>
}
the complete controller
public class datumController : Controller
{
DataEntry db = new DataEntry();
public ActionResult Index()
{
var data = from p in db.categories
select p.categoryName;
SelectList list = new SelectList(data);
ViewBag.Roles = list;
return View();
}
public ActionResult create ()
{
return View();
}
[HttpPost]
public ActionResult FileUpload(HttpPostedFileBase file)
{
if (file != null)
{
string ImageName = System.IO.Path.GetFileName(file.FileName);
string physicalPath = Server.MapPath("~/images/" + ImageName);
// save image in folder
file.SaveAs(physicalPath);
//save new record in database
datum newRecord = new datum();
newRecord.category = Request.Form["category"];
newRecord.description = Request.Form["description"];
newRecord.imagePath = ImageName;
db.data.Add(newRecord);
db.SaveChanges();
}
//Display records
return RedirectToAction("Display");
}
so I should be getting the selected value from the drop down list and attach it to the physical path, check if folder exists if no then create folder and upload image to that folder
Try like below...
string subPath ="ImagesPath"; // your code goes here
bool exists = System.IO.Directory.Exists(Server.MapPath(subPath));
if(!exists)
System.IO.Directory.CreateDirectory(Server.MapPath(subPath));
For further info, please refer below link.
If a folder does not exist, create it
if (file != null && file.ContentLength > 0)
{
string path = Path.Combine(Server.MapPath("~/Images"), Path.GetFileName(file.FileName));
tbl_MixEmp.EmpImage = Path.Combine("~/Images", file.FileName);
file.SaveAs(path);
}

getting image path in jsp

in my project I have to upload the image and show it in user profile view . Now I am successfully storing , I have problem in displaying image. the image is stored path D:/uploads so my image retrieving code in jsp is,
<c:set var="fileanme2" value="${teacherId.getPhoto()}"></c:set>
<%
String uploadFilePath2 = "D:" + "/" + "uploads";
%>
<c:set var="shlash2" value="/"></c:set>
<c:set var="pathValue2" value="<%=uploadFilePath2%>"></c:set>
<c:set var="string4" value="${pathValue2}${shlash2}${fileanme2}" />
<img alt="Image" src="${string4}" width="160" height="160"
class="img-thumbnail">
But image is not displaying , when I inspect the image element in browser in src attrib it showing path as D:/uploads/img when I hover mouse on it shows the path along with the project path how can I get the exact path for displaying image.
no need of any string concatenation and any extra work, you can do it in one line:
<c:set var="filePath" value="D:/uploads/${teacherId.getPhoto()}" />
and solutions for your problem:
1) if you are going to show image from you local file system then do like:
<img src="file:///D|/uploads/image_name.jpg"
width="200"
height="200"
alt="Image"/>
Warning: image may not be accessible when you publish your site.
2) create a servlet to handle GET request's of all images by passing name of image in url like:
#WebServlet("/ImageServlet")
public class ImageServlet extends HttpServlet {
private static final int DEFAULT_BUFFER_SIZE = 10240; // 10KB.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("getting photo...");
String imageName = request.getParameter("imageName");
System.out.println("imageName: "+imageName);
//set your upload path
File imageFile = new File("D:\\uploads\\"+imageName);
System.out.println("file exists: "+imageFile.exists());
// Get content type by filename.
String contentType = getServletContext().getMimeType(imageFile.getName());
// Init servlet response.
response.reset();
response.setBufferSize(DEFAULT_BUFFER_SIZE);
response.setContentType(contentType);
response.setHeader("Content-Length", String.valueOf(imageFile.length()));
response.setHeader("Content-Disposition", "inline; filename=\"" + imageFile.getName() + "\"");
// Prepare streams.
BufferedInputStream input = null;
BufferedOutputStream output = null;
try {
// Open streams.
input = new BufferedInputStream(new FileInputStream(imageFile), DEFAULT_BUFFER_SIZE);
output = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE);
// Write file contents to response.
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
} finally {
// Gently close streams.
close(output);
close(input);
}
// Check if file is actually an image (avoid download of other files by hackers!).
// For all content types, see: http://www.w3schools.com/media/media_mimeref.asp
if (contentType == null || !contentType.startsWith("image")) {
// Do your thing if the file appears not being a real image.
// Throw an exception, or send 404, or show default/warning image, or just ignore it.
response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
return;
}
}
// Helpers (can be refactored to public utility class)
private static void close(Closeable resource) {
if (resource != null) {
try {
resource.close();
} catch (IOException e) {
// Do your thing with the exception. Print it, log it or mail it.
e.printStackTrace();
}
}
}
}
and then in jsp use img tag like:
<img alt="Image"
src="<c:url value="/ImageServlet?imageName=${teacherId.getPhoto()}"/>" />
Source: BalusC image servlet

Primefaces Print Dynamic Images

I tried to load an image dynamically, and everything works.
The image I is loaded and displayed correctly in a dynamic,
I added the tag for printing.
Now if I ask to print the image created dynamically I can not print.
<pou:commandButton value="Print" type="button" icon="ui-icon-print">
<pou:printer target="image" />
</pou:commandButton>
<pou:graphicImage id="image" value="#{printDynamicBean.graphicIMG}" />
My bean does like this:
public StreamedContent getGraphicIMG() {
//Graphic
BufferedImage bufferedImg;
try {
bufferedImg = ImageIO.read(baseImage);
} catch (IOException e) {
}
try {
Graphics2D g2 = bufferedImg.createGraphics();
g2.setColor(Color.black);
int style = Font.BOLD | Font.ITALIC;
Font f1 = new Font("TimesNewRoman", style , 60);
g2.setFont(f1);
g2.drawString("Hello Print", 80, 580);
ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(bufferedImg, "png", os);
graphicIMG = new DefaultStreamedContent(new ByteArrayInputStream(os.toByteArray()), "image/png");
} catch (IOException ex) {
Logger.getLogger(PrintCartelliniBean.class.getName()).log(Level.SEVERE, null, ex);
}
return graphicIMG;
}
it is as if she had forgotten the image created.
Thanks.
using CDI bean you can do this :
#Model
public class ImageBean {
private StreamedContent image;
#Produces
#Named
public StreamedContent getImage() {
if (FacesContext.getCurrentInstance().getRenderResponse()) {
// rendering the view, return a stub StreamedContent to generate right URL.
image = new DefaultStreamedContent();
} else {
// requesting the image
image = your dynamic image;
}
return image;
}
}
in your view : <pou:graphicImage id="image" value="#{image}" />

Resources