How can I use iText to convert HTML with images and hyperlinks to PDF? - pdf

I'm trying to convert HTML to PDF using iTextSharp in an ASP.NET web application that uses both MVC, and web forms. The <img> and <a> elements have absolute and relative URLs, and some of the <img> elements are base64. Typical answers here at SO and Google search results use generic HTML to PDF code with XMLWorkerHelper that looks something like this:
using (var stringReader = new StringReader(xHtml))
{
using (Document document = new Document())
{
PdfWriter writer = PdfWriter.GetInstance(document, stream);
document.Open();
XMLWorkerHelper.GetInstance().ParseXHtml(
writer, document, stringReader
);
}
}
So with sample HTML like this:
<div>
<h3>HTML Works, but Broken in Converted PDF</h3>
<div>Relative local <img>: <img src='./../content/images/kuujinbo_320-30.gif' /></div>
<div>
Base64 <img>:
<img src='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==' />
</div>
<div><a href='/somePage.html'>Relative local hyperlink, broken in PDF</a></div>
<div>
The resulting PDF: (1) is missing all images, and (2) all hyperlink(s) with relative URLs are broken and use a file URI scheme (file///XXX...) instead of pointing to the correct web site.
Some answers here at SO and others from Google search recommend replacing relative URLs with absolute URLs, which is perfectly acceptable for one-off cases. However, globally replacing all <img src> and <a href> attributes with a hard-coded string is unacceptable for this question, so please do not post an answer like that, because it will accordingly be downvoted.
Am looking for a solution that works for many different web applications residing in test, development, and production environments.

Out of the box XMLWorker only understands absolute URIs, so the described issues are expected behavior. The parser can't automagically deduce URI schemes or paths without some additional information.
Implementing an ILinkProvider fixes the broken hyperlink problem, and implementing an IImageProvider fixes the broken image problem. Since both implementations must perform URI resolution, that's the first step. The following helper class does that, and also tries to make web (ASP.NET) context calls (examples follow) as simple as possible:
// resolve URIs for LinkProvider & ImageProvider
public class UriHelper
{
/* IsLocal; when running in web context:
* [1] give LinkProvider http[s] scheme; see CreateBase(string baseUri)
* [2] give ImageProvider relative path starting with '/' - see:
* Join(string relativeUri)
*/
public bool IsLocal { get; set; }
public HttpContext HttpContext { get; private set; }
public Uri BaseUri { get; private set; }
public UriHelper(string baseUri) : this(baseUri, true) {}
public UriHelper(string baseUri, bool isLocal)
{
IsLocal = isLocal;
HttpContext = HttpContext.Current;
BaseUri = CreateBase(baseUri);
}
/* get URI for IImageProvider to instantiate iTextSharp.text.Image for
* each <img> element in the HTML.
*/
public string Combine(string relativeUri)
{
/* when running in a web context, the HTML is coming from a MVC view
* or web form, so convert the incoming URI to a **local** path
*/
if (HttpContext != null && !BaseUri.IsAbsoluteUri && IsLocal)
{
return HttpContext.Server.MapPath(
// Combine() checks directory traversal exploits
VirtualPathUtility.Combine(BaseUri.ToString(), relativeUri)
);
}
return BaseUri.Scheme == Uri.UriSchemeFile
? Path.Combine(BaseUri.LocalPath, relativeUri)
// for this example we're assuming URI.Scheme is http[s]
: new Uri(BaseUri, relativeUri).AbsoluteUri;
}
private Uri CreateBase(string baseUri)
{
if (HttpContext != null)
{ // running on a web server; need to update original value
var req = HttpContext.Request;
baseUri = IsLocal
// IImageProvider; absolute virtual path (starts with '/')
// used to convert to local file system path. see:
// Combine(string relativeUri)
? req.ApplicationPath
// ILinkProvider; absolute http[s] URI scheme
: req.Url.GetLeftPart(UriPartial.Authority)
+ HttpContext.Request.ApplicationPath;
}
Uri uri;
if (Uri.TryCreate(baseUri, UriKind.RelativeOrAbsolute, out uri)) return uri;
throw new InvalidOperationException("cannot create a valid BaseUri");
}
}
Implementing ILinkProvider is pretty simple now that UriHelper gives the base URI. We just need the correct URI scheme (file or http[s]):
// make hyperlinks with relative URLs absolute
public class LinkProvider : ILinkProvider
{
// rfc1738 - file URI scheme section 3.10
public const char SEPARATOR = '/';
public string BaseUrl { get; private set; }
public LinkProvider(UriHelper uriHelper)
{
var uri = uriHelper.BaseUri;
/* simplified implementation that only takes into account:
* Uri.UriSchemeFile || Uri.UriSchemeHttp || Uri.UriSchemeHttps
*/
BaseUrl = uri.Scheme == Uri.UriSchemeFile
// need trailing separator or file paths break
? uri.AbsoluteUri.TrimEnd(SEPARATOR) + SEPARATOR
// assumes Uri.UriSchemeHttp || Uri.UriSchemeHttps
: BaseUrl = uri.AbsoluteUri;
}
public string GetLinkRoot()
{
return BaseUrl;
}
}
IImageProvider only requires implementing a single method, Retrieve(string src), but Store(string src, Image img) is easy - note inline comments there and for GetImageRootPath():
// handle <img> elements in HTML
public class ImageProvider : IImageProvider
{
private UriHelper _uriHelper;
// see Store(string src, Image img)
private Dictionary<string, Image> _imageCache =
new Dictionary<string, Image>();
public virtual float ScalePercent { get; set; }
public virtual Regex Base64 { get; set; }
public ImageProvider(UriHelper uriHelper) : this(uriHelper, 67f) { }
// hard-coded based on general past experience ^^^
// but call the overload to supply your own
public ImageProvider(UriHelper uriHelper, float scalePercent)
{
_uriHelper = uriHelper;
ScalePercent = scalePercent;
Base64 = new Regex( // rfc2045, section 6.8 (alphabet/padding)
#"^data:image/[^;]+;base64,(?<data>[a-z0-9+/]+={0,2})$",
RegexOptions.Compiled | RegexOptions.IgnoreCase
);
}
public virtual Image ScaleImage(Image img)
{
img.ScalePercent(ScalePercent);
return img;
}
public virtual Image Retrieve(string src)
{
if (_imageCache.ContainsKey(src)) return _imageCache[src];
try
{
if (Regex.IsMatch(src, "^https?://", RegexOptions.IgnoreCase))
{
return ScaleImage(Image.GetInstance(src));
}
Match match;
if ((match = Base64.Match(src)).Length > 0)
{
return ScaleImage(Image.GetInstance(
Convert.FromBase64String(match.Groups["data"].Value)
));
}
var imgPath = _uriHelper.Combine(src);
return ScaleImage(Image.GetInstance(imgPath));
}
// not implemented to keep the SO answer (relatively) short
catch (BadElementException ex) { return null; }
catch (IOException ex) { return null; }
catch (Exception ex) { return null; }
}
/*
* always called after Retrieve(string src):
* [1] cache any duplicate <img> in the HTML source so the image bytes
* are only written to the PDF **once**, which reduces the
* resulting file size.
* [2] the cache can also **potentially** save network IO if you're
* running the parser in a loop, since Image.GetInstance() creates
* a WebRequest when an image resides on a remote server. couldn't
* find a CachePolicy in the source code
*/
public virtual void Store(string src, Image img)
{
if (!_imageCache.ContainsKey(src)) _imageCache.Add(src, img);
}
/* XMLWorker documentation for ImageProvider recommends implementing
* GetImageRootPath():
*
* http://demo.itextsupport.com/xmlworker/itextdoc/flatsite.html#itextdoc-menu-10
*
* but a quick run through the debugger never hits the breakpoint, so
* not sure if I'm missing something, or something has changed internally
* with XMLWorker....
*/
public virtual string GetImageRootPath() { return null; }
public virtual void Reset() { }
}
Based on the XML Worker documentation it's pretty straightforward to hook the implementations of ILinkProvider and IImageProvider above into a simple parser class:
/* a simple parser that uses XMLWorker and XMLParser to handle converting
* (most) images and hyperlinks internally
*/
public class SimpleParser
{
public virtual ILinkProvider LinkProvider { get; set; }
public virtual IImageProvider ImageProvider { get; set; }
public virtual HtmlPipelineContext HtmlPipelineContext { get; set; }
public virtual ITagProcessorFactory TagProcessorFactory { get; set; }
public virtual ICSSResolver CssResolver { get; set; }
/* overloads simplfied to keep SO answer (relatively) short. if needed
* set LinkProvider/ImageProvider after instantiating SimpleParser()
* to override the defaults (e.g. ImageProvider.ScalePercent)
*/
public SimpleParser() : this(null) { }
public SimpleParser(string baseUri)
{
LinkProvider = new LinkProvider(new UriHelper(baseUri, false));
ImageProvider = new ImageProvider(new UriHelper(baseUri, true));
HtmlPipelineContext = new HtmlPipelineContext(null);
// another story altogether, and not implemented for simplicity
TagProcessorFactory = Tags.GetHtmlTagProcessorFactory();
CssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(true);
}
/*
* when sending XHR via any of the popular JavaScript frameworks,
* <img> tags are **NOT** always closed, which results in the
* infamous iTextSharp.tool.xml.exceptions.RuntimeWorkerException:
* 'Invalid nested tag a found, expected closing tag img.' a simple
* workaround.
*/
public virtual string SimpleAjaxImgFix(string xHtml)
{
return Regex.Replace(
xHtml,
"(?<image><img[^>]+)(?<=[^/])>",
new MatchEvaluator(match => match.Groups["image"].Value + " />"),
RegexOptions.IgnoreCase | RegexOptions.Multiline
);
}
public virtual void Parse(Stream stream, string xHtml)
{
xHtml = SimpleAjaxImgFix(xHtml);
using (var stringReader = new StringReader(xHtml))
{
using (Document document = new Document())
{
PdfWriter writer = PdfWriter.GetInstance(document, stream);
document.Open();
HtmlPipelineContext
.SetTagFactory(Tags.GetHtmlTagProcessorFactory())
.SetLinkProvider(LinkProvider)
.SetImageProvider(ImageProvider)
;
var pdfWriterPipeline = new PdfWriterPipeline(document, writer);
var htmlPipeline = new HtmlPipeline(HtmlPipelineContext, pdfWriterPipeline);
var cssResolverPipeline = new CssResolverPipeline(CssResolver, htmlPipeline);
XMLWorker worker = new XMLWorker(cssResolverPipeline, true);
XMLParser parser = new XMLParser(worker);
parser.Parse(stringReader);
}
}
}
}
As commented inline, SimpleAjaxImgFix(string xHtml) specifically handles XHR that may send unclosed <img> tags, which is valid HTML, but invalid XML that will break XMLWorker . A simple explanation & implementation of how to receive a PDF or other binary data with XHR and iTextSharp can be found here.
A Regex was used in SimpleAjaxImgFix(string xHtml) so that anyone using (copy/paste?) the code doesn't need to add another nuget package, but a HTML parser like HtmlAgilityPack should be used, since it's turns this:
<div><img src='a.gif'><br><hr></div>
into this:
<div><img src='a.gif' /><br /><hr /></div>
with only a few lines of code:
var hDocument = new HtmlDocument()
{
OptionWriteEmptyNodes = true,
OptionAutoCloseOnEnd = true
};
hDocument.LoadHtml("<div><img src='a.gif'><br><hr></div>");
var closedTags = hDocument.DocumentNode.WriteTo();
Also of note - use SimpleParser.Parse() above as a general blueprint to additionally implement a custom ICSSResolver or ITagProcessorFactory, which is explained in the documentation.
Now the issues described in the question should be taken care of. Called from a MVC Action Method:
[HttpPost] // some browsers have URL length limits
[ValidateInput(false)] // or throws HttpRequestValidationException
public ActionResult Index(string xHtml)
{
Response.ContentType = "application/pdf";
Response.AppendHeader(
"Content-Disposition", "attachment; filename=test.pdf"
);
var simpleParser = new SimpleParser();
simpleParser.Parse(Response.OutputStream, xHtml);
return new EmptyResult();
}
or from a Web Form that gets HTML from a server control:
Response.ContentType = "application/pdf";
Response.AppendHeader("Content-Disposition", "attachment; filename=test.pdf");
using (var stringWriter = new StringWriter())
{
using (var htmlWriter = new HtmlTextWriter(stringWriter))
{
ConvertControlToPdf.RenderControl(htmlWriter);
}
var simpleParser = new SimpleParser();
simpleParser.Parse(Response.OutputStream, stringWriter.ToString());
}
Response.End();
or a simple HTML file with hyperlinks and images on the file system:
<h1>HTML Page 00 on Local File System</h1>
<div>
<div>
Relative <img>: <img src='Images/alt-gravatar.png' />
</div>
<div>
Hyperlink to file system HTML page:
<a href='file-system-html-01.html'>Page 01</a>
</div>
</div>
or HTML from a remote web site:
<div>
<div>
<img width="200" alt="Wikipedia Logo"
src="portal/wikipedia.org/assets/img/Wikipedia-logo-v2.png">
</div>
<div lang="en">
English
</div>
<div lang="en">
iText
</div>
</div>
Above two HTML snippets run from a console app:
var filePaths = Path.Combine(basePath, "file-system-html-00.html");
var htmlFile = File.ReadAllText(filePaths);
var remoteUrl = Path.Combine(basePath, "wikipedia.html");
var htmlRemote = File.ReadAllText(remoteUrl);
var outputFile = Path.Combine(basePath, "filePaths.pdf");
var outputRemote = Path.Combine(basePath, "remoteUrl.pdf");
using (var stream = new FileStream(outputFile, FileMode.Create))
{
var simpleParser = new SimpleParser(basePath);
simpleParser.Parse(stream, htmlFile);
}
using (var stream = new FileStream(outputRemote, FileMode.Create))
{
var simpleParser = new SimpleParser("https://wikipedia.org");
simpleParser.Parse(stream, htmlRemote);
}
Quite a long answer, but taking a look at questions here at SO tagged html, pdf, and itextsharp, as of this writing (2016-02-23) there are 776 results against 4,063 total tagged itextsharp - that's 19%.

Very helpful post,
I was problem to render images in my report html to pdf. with your post I could do it.
I'm working with asp.mvc 5.
I only have to change this method of the ImageProviderClass
public virtual string GetImageRootPath() { return null; }
to
public virtual string GetImageRootPath() { HostingEnvironment.MapPath("~/Content/Images/") }
thanks!

Related

Support to convert the HTML to PDF in Xamarin Forms

With the reference of following StackOverflow suggestion,
Convert HTML to PDF in .NET
I tried to convert the HTML file to PDF using HtmlRenderer.PdfSharp but unfortunately it shows compatible error like below,
HtmlRendererCore.PdfSharpCore 1.0.1 is not compatible with netstandard2.0 (.NETStandard,Version=v2.0). Package HtmlRendererCore.PdfSharpCore 1.0.1 supports: netcoreapp2.0 (.NETCoreApp,Version=v2.0)
HtmlRenderer.Core 1.5.0.5 is not compatible with monoandroid90 (MonoAndroid,Version=v9.0). Package HtmlRenderer.Core 1.5.0.5 supports:
- net20 (.NETFramework,Version=v2.0)
- net30 (.NETFramework,Version=v3.0)
- net35-client (.NETFramework,Version=v3.5,Profile=Client)
- net40-client (.NETFramework,Version=v4.0,Profile=Client)
- net45 (.NETFramework,Version=v4.5)
HtmlRendererCore.PdfSharpCore 1.0.1 is not compatible with monoandroid90 (MonoAndroid,Version=v9.0). Package HtmlRendererCore.PdfSharpCore 1.0.1 supports: netcoreapp2.0 (.NETCoreApp,Version=v2.0)
And I tried with wkhtmltopdf too but it throws similar error in android and other platform projects.
My requirement is to convert the HTML file to PDF file only (no need to view the PDF file, just to save it in local path).
Can anyone please provide suggestions?
Note : Need open source suggestion :)
Awaiting for your suggestions !!!
Support to convert the HTML to PDF in Xamarin Forms
You can read the HTML as a stream and store it into local like below,
public static class FileManager
{
public static async Task<MemoryStream> DownloadFileAsStreamAsync(string url)
{
try
{
var stream = new MemoryStream();
using (var httpClient = new HttpClient())
{
var downloadStream = await httpClient.GetStreamAsync(new Uri(url));
if (downloadStream != null)
{
await downloadStream.CopyToAsync(stream);
}
}
return stream;
}
catch (Exception exception)
{
return null;
}
}
public static async Task<bool> DownloadAndWriteIntoNewFile(string url, string fileName)
{
var stream = await DownloadFileAsStreamAsync(url);
if (stream == null || stream.Length == 0)
return false;
var filePath = GetFilePath(fileName);
if (!File.Exists(filePath))
return false;
File.Delete(filePath);
// Create file.
using (var createdFile = File.Create(filePath))
{
}
// Open and write into file.
using (var openFile = File.Open(filePath, FileMode.Open, FileAccess.ReadWrite))
{
stream.WriteTo(openFile);
}
return true;
}
public static string GetFilePath(string fileName)
{
var filePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), fileName);
return filePath;
}
public static void WriteAsText(string filePath, string contents)
{
File.WriteAllText(filePath, contents);
}
public static string ReadAsText(string filePath)
{
return File.ReadAllText(filePath);
}
}
You can read a stored pdf file and displayed using webview like below,
private async void HtmlToPDF()
{
await FileManager.DownloadAndWriteIntoNewFile("https://www.google.co.in/?gws_rd=ssl", "SavePDF.pdf");
var filePath = FileManager.GetFilePath("SavePDF.pdf");
var pdfString = FileManager.ReadAsText(filePath);
var webView = new WebView
{
Source = new HtmlWebViewSource
{
Html = pdfString
}
};
this.Content = webView;
}
And the output below,
Likewise, you can save HTML as PDF and do what you want..
you can use the HtmlToPdfConverter
private void ConvertUrlToPdf()
{
try {
String serverIPAddress = serverIP.Text;
uint serverPortNumber = uint.Parse (serverPort.Text);
// create the HTML to PDF converter object
HtmlToPdfConverter htmlToPdfConverter = new HtmlToPdfConverter (serverIPAddress, serverPortNumber);
// set service password if necessary
if (serverPassword.Text.Length > 0)
htmlToPdfConverter.ServicePassword = serverPassword.Text;
// set PDF page size
htmlToPdfConverter.PdfDocumentOptions.PdfPageSize = PdfPageSize.A4;
// set PDF page orientation
htmlToPdfConverter.PdfDocumentOptions.PdfPageOrientation = PdfPageOrientation.Portrait;
// convert the HTML page from given URL to PDF in a buffer
byte[] pdfBytes = htmlToPdfConverter.ConvertUrl (urlToConvert.Text);
string documentsFolder = Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments);
string outPdfFile = System.IO.Path.Combine (documentsFolder, "EvoHtmlToPdf.pdf");
// write the PDF buffer in output file
System.IO.File.WriteAllBytes (outPdfFile, pdfBytes);
// open the PDF document in the default PDF viewer
UIDocumentInteractionController pdfViewer = UIDocumentInteractionController.FromUrl (Foundation.NSUrl.FromFilename (outPdfFile));
pdfViewer.PresentOpenInMenu (this.View.Frame, this.View, true);
} catch (Exception ex) {
UIAlertView alert = new UIAlertView ();
alert.Title = "Error";
alert.AddButton ("OK");
alert.Message = ex.Message;
alert.Show ();
}
}
another
you can see thisurl

Library to verify OAuth 1.0a signature in ASP.NET Core

I need to validate OAuth 1.0a (RFC 5849) requests on an ASP.NET Core site. Upgrading the client to OAuth 2.0 or anything else is not an option. I understand the spec, but implementing the verification process for the oauth_signature seems like it would be a bit fragile, and surely there's no need to reinvent the wheel here.
Does .NET Core have any built-in classes for handling this? Ideally, something where you just pass in the HttpRequest and the secret key and it tells you if the signature is valid?
If there's nothing built in, any recommendations on third-party libraries that could handle this for me?
I really didn't feel comfortable taking a dependency hit on this one by bringing in a third-party NuGet package. Many of the options provided far more than I needed, and most were (understandably) no longer in active development or supported. Taking on an unsupported "black box" dependency with anything related to security doesn't sit quite right with me.
So I rolled my own implementation for just the subset of features that I needed to support (verification only, and OAuth parameters passed as form post data). This is not meant to be a complete implementation, but can serve as a starting point for anyone else who finds themselves in a similar situation and isn't interested in bringing in a dependency.
The latest code is on GitHub.
public static class OAuth1Utilities
{
private static readonly Lazy<bool[]> UnreservedCharacterMask = new Lazy<bool[]>(CreateUnreservedCharacterMask);
public static string EncodeString(string value)
{
byte[] characterBytes = Encoding.UTF8.GetBytes(value);
StringBuilder encoded = new StringBuilder();
foreach (byte character in characterBytes)
{
if (UnreservedCharacterMask.Value[character])
{
encoded.Append((char)character);
}
else
{
encoded.Append($"%{character:X2}");
}
}
return encoded.ToString();
}
public static string GetBaseStringUri(HttpRequest request)
{
StringBuilder baseStringUri = new StringBuilder();
baseStringUri.Append(request.Scheme.ToLowerInvariant());
baseStringUri.Append("://");
baseStringUri.Append(request.Host.ToString().ToLowerInvariant());
baseStringUri.Append(request.Path.ToString().ToLowerInvariant());
return baseStringUri.ToString();
}
public static string GetNormalizedParameterString(HttpRequest request)
{
var parameters = new List<(string key, string value)>();
foreach (var queryItem in request.Query)
{
foreach (var queryValue in queryItem.Value)
{
parameters.Add((queryItem.Key, queryValue));
}
}
foreach (var formItem in request.Form)
{
foreach (var formValue in formItem.Value)
{
parameters.Add((formItem.Key, formValue));
}
}
parameters.RemoveAll(_ => _.key == "oauth_signature");
parameters = parameters
.Select(_ => (key: EncodeString(_.key), value: EncodeString(_.value)))
.OrderBy(_ => _.key)
.ThenBy(_ => _.value).ToList();
return string.Join("&", parameters.Select(_ => $"{_.key}={_.value}"));
}
public static string GetSignature(HttpRequest request, string clientSharedSecret, string tokenSharedSecret)
{
string signatureBaseString = GetSignatureBaseString(request);
return GetSignature(signatureBaseString, clientSharedSecret, tokenSharedSecret);
}
public static string GetSignature(string signatureBaseString, string clientSharedSecret, string tokenSharedSecret)
{
string key = $"{EncodeString(clientSharedSecret)}&{EncodeString(tokenSharedSecret)}";
var signatureAlgorithm = new HMACSHA1(Encoding.ASCII.GetBytes(key));
byte[] digest = signatureAlgorithm.ComputeHash(Encoding.ASCII.GetBytes(signatureBaseString));
return Convert.ToBase64String(digest);
}
public static string GetSignatureBaseString(HttpRequest request)
{
StringBuilder signatureBaseString = new StringBuilder();
signatureBaseString.Append(request.Method.ToUpperInvariant());
signatureBaseString.Append("&");
signatureBaseString.Append(EncodeString(GetBaseStringUri(request)));
signatureBaseString.Append("&");
signatureBaseString.Append(EncodeString(GetNormalizedParameterString(request)));
return signatureBaseString.ToString();
}
public static bool VerifySignature(HttpRequest request, string clientSharedSecret, string tokenSharedSecret)
{
string actualSignature = request.Form["oauth_signature"];
string expectedSignature = GetSignature(request, clientSharedSecret, tokenSharedSecret);
return expectedSignature == actualSignature;
}
private static bool[] CreateUnreservedCharacterMask()
{
bool[] mask = new bool[byte.MaxValue];
// hyphen
mask[45] = true;
// period
mask[46] = true;
// 0-9
for (int pos = 48; pos <= 57; pos++)
{
mask[pos] = true;
}
// A-Z
for (int pos = 65; pos <= 90; pos++)
{
mask[pos] = true;
}
// underscore
mask[95] = true;
// a-z
for (int pos = 97; pos <= 122; pos++)
{
mask[pos] = true;
}
// tilde
mask[126] = true;
return mask;
}
}

Files uploaded but not appearing on server

I use the code stated here to upload files through a webapi http://bartwullems.blogspot.pe/2013/03/web-api-file-upload-set-filename.html. I also made the following api to list all the files I have :
[HttpPost]
[Route("sharepoint/imageBrowser/listFiles")]
[SharePointContextFilter]
public async Task<HttpResponseMessage> Read()
{
string pathImages = HttpContext.Current.Server.MapPath("~/Content/images");
DirectoryInfo d = new DirectoryInfo(pathImages);//Assuming Test is your Folder
FileInfo[] Files = d.GetFiles(); //Getting Text files
List<object> lst = new List<object>();
foreach (FileInfo f in Files)
{
lst.Add(new
{
name = f.Name,
type = "f",
size = f.Length
});
}
return Request.CreateResponse(HttpStatusCode.OK, lst);
}
When calling this api, all the files uploaded are listed. But when I go to azure I dont see any of them (Content.png is a file I manually uploaded to azure)
Why are the files listed if they dont appear on azure.
According to your description, I suggest you could firstly use azure kudu console to locate the right folder in the azure web portal to see the image file.
Open kudu console:
In the kudu click the debug console and locate the site\wwwroot\yourfilefolder
If you find your file is still doesn't upload successfully, I guess there maybe something wrong with your upload codes. I suggest you could try below codes.
Notice: You need add image folder in the wwwort folder.
{
public class UploadingController : ApiController
{
public async Task<HttpResponseMessage> PostFile()
{
// Check if the request contains multipart/form-data.
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
string root = Environment.GetEnvironmentVariable("HOME").ToString() + "\\site\\wwwroot\\images";
//string root = HttpContext.Current.Server.MapPath("~/images");
var provider = new FilenameMultipartFormDataStreamProvider(root);
try
{
StringBuilder sb = new StringBuilder(); // Holds the response body
// Read the form data and return an async task.
await Request.Content.ReadAsMultipartAsync(provider);
// This illustrates how to get the form data.
foreach (var key in provider.FormData.AllKeys)
{
foreach (var val in provider.FormData.GetValues(key))
{
sb.Append(string.Format("{0}: {1}\n", key, val));
}
}
// This illustrates how to get the file names for uploaded files.
foreach (var file in provider.FileData)
{
FileInfo fileInfo = new FileInfo(file.LocalFileName);
sb.Append(string.Format("Uploaded file: {0} ({1} bytes)\n", fileInfo.Name, fileInfo.Length));
}
return new HttpResponseMessage()
{
Content = new StringContent(sb.ToString())
};
}
catch (System.Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
}
}
}
public class FilenameMultipartFormDataStreamProvider : MultipartFormDataStreamProvider
{
public FilenameMultipartFormDataStreamProvider(string path) : base(path)
{
}
public override string GetLocalFileName(System.Net.Http.Headers.HttpContentHeaders headers)
{
var name = !string.IsNullOrWhiteSpace(headers.ContentDisposition.FileName) ? headers.ContentDisposition.FileName : Guid.NewGuid().ToString();
return name.Replace("\"", string.Empty);
}
}
}
Result:

Silverlight bingMapContril using LocalproxyPage to downLoad MapTiles Extremely Slow

as we know silverlight5 has ability to get pageElement's visual so we can print or save them as pictrue.but if your MapTilesSource uri is in a differentDomain to your silverlight Application host site,you can not get BingMapControl's visual,because of "cross-domain problem",clr would throw a System.Security.SecurityException.
To avoid this problem I add a Proxy aspx page in the silverlight host site,which can send bingMap TileImage request to the remote MapTilesService.
here is my customer Class inherit from TileSource:
public class GoogleTileSource : TileSource
{
public GoogleTileSource()
: base("http://mt{0}.google.cn/vt/lyrs={1}#180000000&hl=zh-CN&gl=cn&z={2}&x={3}&y={4}")
{
this.Type = GoogleTileType.Hybrid;
}
public override Uri GetUri(int x, int y, int zoomLevel)
{
string TargetUrl = string.Format(this.UriFormat, this.Server, (char)this.Type, zoomLevel, x, y);
return new Uri(string.Format(http://localhost:52879/MapTilesServerProxy.aspx + "?sourceUrl={0}", TargetUrl));
//return new Uri(string.Format(this.UriFormat, this.Server, (char)this.Type, zoomLevel, x, y));
}
public int Server
{
get;
set;
}
public GoogleTileType Type
{
get;
set;
}
}
here is my proxy page code:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="MapTilesServerProxy.aspx.cs" Inherits="AeroZH.Web.MapTilesServerProxy" %>
<%# Import Namespace=System.Net %>
<%# Import Namespace=System.IO %>
<%# Import Namespace=System.Diagnostics %>
<script runat="server">
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
ProxyRequest();
}
private void ProxyRequest()
{
try
{
string url = "";
url = this.Page.Request.Url.AbsoluteUri.Split(new string[] { "?sourceUrl=" }, StringSplitOptions.RemoveEmptyEntries)[1];
Debug.WriteLine("url:" + url);
Debug.WriteLine(url + "——requestTime:" + System.DateTime.Now);
HttpWebRequest loHttp = (HttpWebRequest)WebRequest.Create(url);
loHttp.Timeout = 10000; // 10 secs
loHttp.UserAgent = "Web Client";
HttpWebResponse loWebResponse = (HttpWebResponse)loHttp.GetResponse();
Debug.WriteLine(url + "——responseTime:" + System.DateTime.Now);
using (Stream inputStream = loWebResponse.GetResponseStream())
{
byte[] buffer = new byte[4096 * 100];
int bytesRead;
do
{
bytesRead = inputStream.Read(buffer, 0, buffer.Length);
} while (bytesRead != 0);
Response.BinaryWrite(buffer);
Response.End();
}
loWebResponse.Close();
if (loHttp != null)
loHttp.Abort();
}
catch (Exception e)
{
Debug.WriteLine(e.Message);
}
}
after this work,bingMapcontrol successfully make its image request thought the proxy page ,and the ProxyPage's request get response form remote server is also success.but only a few mapTiles show in the map.
I using debug.write to trace response status,almost everyRequest has correct response,i don't know why only few mapTiles show in map.
First off, using Google map tiles in Bing Maps is against the terms of use of both the Bing Maps and Google Maps terms of use.
Secondly, The Bing Maps Silverlight control is nearing end of life. The documentation is already offline and it won't be long before the control is disabled. No new development should be one with it. Also, the end of life for Silverlight in general was announced a few years ago.

ASP.NET WebApi file upload using guid and file extension

I currently am able to save a file being uploaded to a WebAPI controller, but I'd like to be able to save the file as a guid with the correct file name extension so it can be viewed correctly.
Code:
[ValidationFilter]
public HttpResponseMessage UploadFile([FromUri]string AdditionalInformation)
{
var task = this.Request.Content.ReadAsStreamAsync();
task.Wait();
using (var requestStream = task.Result)
{
try
{
// how can I get the file extension of the content and append this to the file path below?
using (var fileStream = File.Create(HttpContext.Current.Server.MapPath("~/" + Guid.NewGuid().ToString())))
{
requestStream.CopyTo(fileStream);
}
}
catch (IOException)
{
throw new HttpResponseException(HttpStatusCode.InternalServerError);
}
}
HttpResponseMessage response = new HttpResponseMessage();
response.StatusCode = HttpStatusCode.Created;
return response;
}
I can't seem to get a handle on the actual filename of the content. I thought headers.ContentDisposition.FileName might be a candidate but that doesn't seem to get populated.
Thanks for the comments above which pointed me in the right direction.
To clarify the final solution, I used a MultipartFormDataStreamProvider which streams the file automatically. The code is in another question I posted to a different problem here:
MultipartFormDataStreamProvider and preserving current HttpContext
My full provider code is listed below. The key to generating the guid file name is to override the GetLocalFileName function and use the headers.ContentDisposition property. The provider handles the streaming of the content to file.
public class MyFormDataStreamProvider : MultipartFormDataStreamProvider
{
public MyFormDataStreamProvider (string path)
: base(path)
{ }
public override Stream GetStream(HttpContent parent, HttpContentHeaders headers)
{
// restrict what images can be selected
var extensions = new[] { "png", "gif", "jpg" };
var filename = headers.ContentDisposition.FileName.Replace("\"", string.Empty);
if (filename.IndexOf('.') < 0)
return Stream.Null;
var extension = filename.Split('.').Last();
return extensions.Any(i => i.Equals(extension, StringComparison.InvariantCultureIgnoreCase))
? base.GetStream(parent, headers)
: Stream.Null;
}
public override string GetLocalFileName(System.Net.Http.Headers.HttpContentHeaders headers)
{
// override the filename which is stored by the provider (by default is bodypart_x)
string oldfileName = headers.ContentDisposition.FileName.Replace("\"", string.Empty);
string newFileName = Guid.NewGuid().ToString() + Path.GetExtension(oldfileName);
return newFileName;
}
}