I'm using a Samba File Server for copy files from my Android device to a shared folder on Windows. With .txt files i haven't any problems, works fine, but I tried to copy a .jpg file into shared folder and it fails. I searched a lot of codes from internet but anyone solved my problem.
I managed to copy the image, but when I open it, is damaged.
Does anyone have any sample code?
My code is this:
Java.IO.File mfile = new Java.IO.File(item.FullName);
var mSharedFolderCalidad = new SmbFile(AppGlobalConfigSoftware.Instance.Parameters.PathToDownloadCalidad + item.Name);
//If exists don't create another time
if (!mSharedFolderCalidad.Exists())
mSharedFolderCalidad.CreateNewFile();
InputStream inFile = new FileInputStream(mfile);
SmbFileOutputStream sfos = new SmbFileOutputStream(mSharedFolderCalidad);
byte[] buf = new byte[1024];
int len;
while ((len = inFile.Read(buf)) > 0)
{
sfos.Write(buf, 0, len);
}
inFile.Close();
sfos.Close();
All help is appreciated.
Thank you.
You can use Media.Plugin from nuget to take photo firstly.
var file = await CrossMedia.Current.TakePhotoAsync(new StoreCameraMediaOptions
{
PhotoSize = PhotoSize.Medium,
});
public byte[] ReadFully(Stream input)
{
byte[] buffer = new byte[16*1024];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
return ms.ToArray();
}
}
MediaFile has GetStream().
You could use this to the Stream and then convert that to a byte[]. Here is one way to do that:
Define a stream
Stream imageStream;
And init it after you take the photo .
imageStream = file.GetStream();
var imageArr= ReadFully(imageStream );
And then write it to your folder .
Related
I'm trying to upload a file from an .jsp.
This is the .jsp part
<form class="user" action="./messaggio" method="POST" enctype="multipart/form-data">
//other input
<input type="file" name="allegato" id="allegato">
//other things
The file should be converted in a Base64 String and stored into the DB.
I'm using Tomcat 8.5 and 3.1 Servlet and i have to do it server side without using JS.
I really don't know how to continue. I've looking on stackoverflow without understandig well what's the exact process to follow.
I'm not looking for the code, but the flow of the event.
Sorry for my english.
Thanks.
Found the solution:
Part filePart = request.getPart("file");
InputStream fileContent = filePart.getInputStream();
File f = new File(getServletContext() + "temp");
OutputStream outputStream = null;
if (isMultipart) {
try {
outputStream = new FileOutputStream(f);
int read = 0;
byte[] bytes = new byte[1024];
while ((read = fileContent.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
allegato = //criptMethodHere
} finally {
if (outputStream != null) {
outputStream.close();
f.delete();
}
}
I am doing html to pdf file . Its Downloading instantly . I dont want download instantly. i want to save the file in my project folder once converted.
My C# Code
string html ="<table><tr><td>some contents</td></tr></table>";
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=WelcomeLetter.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
StringReader sr = new StringReader(table);
Document ResultPDF = new Document(iTextSharp.text.PageSize.A4, 25, 10, 20, 30);
PdfPTable Headtable = new PdfPTable(7);
Headtable.TotalWidth = 525f;
Headtable.LockedWidth = true;
Headtable.HeaderRows = 5;
Headtable.FooterRows = 2;
Headtable.KeepTogether = true;
HTMLWorker htmlparser = new HTMLWorker(ResultPDF);
PdfWriter.GetInstance(ResultPDF, Response.OutputStream);
ResultPDF.Open();
htmlparser.Parse(sr);
ResultPDF.Close();
Response.Write(ResultPDF);
Response.End();
For saving pdf file locally in your project folder you can use FileStream class like this.
FileStream stream = new FileStream(filePath, FileMode.Create);//Here filePath is path of your project folder.
Now use this stream instead of using Response.OutputStream when you create instance of PdfWriter object.
PdfWriter.GetInstance(ResultPDF, stream);
Now do not use Responce.Write as you don't want to download your file.And close your stream at end.
stream.Close();
I'm going to combine everyone's answer into one that you should be able to drop in and use. If this works, I would accept Manish Parakhiya's answer because that had the most important part.
First, I'm going to assume you are using a recent version of iTextSharp. I think 5.5.5 is the most recent version. Second, because of this, I'm going to restructure your code a bit in order to use the using pattern. If you're stuck on an older obsolete unsupported version like 4.1.6 you'll need to re-adjust.
Almost every tutorial out there shows you that you can bind directly the Response.OutputStream. This is 100% valid but I would argue that it is also a really bad idea. Instead, bind to a more generic MemoryStream. This makes debugging much easier and your code will port and adapt that much easier.
The below code includes comments about each of the changes and what things are actually doing. The top section is all about creating a PDF from a string of HTML. The bottom actually does something with it, including writing it to disk and/or streaming it to a browser.
//Will hold our PDF eventually
Byte[] bytes;
//HTML that we want to parse
string html = "<table><tr><td>some contents</td></tr></table>";
//Create a MemoryStream to write our PDF to
using (var ms = new MemoryStream()) {
//Create our document abstraction
using (var ResultPDF = new Document(iTextSharp.text.PageSize.A4, 25, 10, 20, 30)) {
//Bind a writer to our Document abstraction and our stream
using (var writer = PdfWriter.GetInstance(ResultPDF, ms)) {
//Open the PDF for writing
ResultPDF.Open();
//Parse our HTML using the old, obsolete, not support parser
using (var sw = new StringWriter()) {
using (var hw = new HtmlTextWriter(sw)) {
using (var sr = new StringReader(html)) {
using (var htmlparser = new HTMLWorker(ResultPDF)) {
htmlparser.Parse(sr);
}
}
}
}
//Close the PDF
ResultPDF.Close();
}
}
//Grab the raw bytes of the PDF
bytes = ms.ToArray();
}
//At this point, the bytes variable holds a valid PDF file.
//You can write it disk:
System.IO.File.WriteAllBytes("your file path here", bytes);
//You can also send it to a browser:
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=WelcomeLetter.pdf");
Response.BinaryWrite(bytes);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
//Never do the next line, it doesn't do what you think it does and actually produces corrupt PDFs
//Response.Write(ResultPDF); //BAD!!!!!!
Response.End();
string tempDirectory = Session.SessionID.ToString();
string location = Path.Combine(Server.MapPath(
WebConfigurationManager.AppSettings["PathSet"].ToString()), tempDirectory);
if (!Directory.Exists(location))
{
Directory.CreateDirectory(location);
}
string fileName="abc.pdf";
filePath = Path.Combine(location, fileName);
As the title sugests, I have a list of SPFiles (sharepoint attachments) and I need to compress it and push to user download it.
I`ve looked for some examples here and tryed to code something but yet no success.
Here follow my last try until now
using (var stream = new MemoryStream())
{
using (var archive = new ZipArchive(stream, ZipArchiveMode.Create, true))
{
foreach (SPFile item in lstFiles)
{
//string nomeEntrada = item.Substring(item.LastIndexOf("/") + 1);
var file = archive.CreateEntry(item.Name);
using (var entryStream = file.Open())
using (var streamWriter = new BinaryWriter(entryStream))
{
byte[] bytes = item.OpenBinary();
streamWriter.Write(bytes, 0, bytes.Length);
}
}
}
//For testing only, to check if the .zip is beeing correctly generated
using (FileStream file = new FileStream("C:\\teste\\file.zip", FileMode.Create, System.IO.FileAccess.Write))
{
stream.Seek(0, SeekOrigin.Begin);
stream.CopyTo(file);
}
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = "application/x-zip-compressed";
HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=anexos.zip");
HttpContext.Current.Response.BinaryWrite(stream.ToArray());
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.Close();
HttpContext.Current.ApplicationInstance.CompleteRequest();
HttpContext.Current.Response.End();
}
PS: I do not want to save the file in server directory, that was just a test to check if the file was OK
I created an Application Page and redirected user to it. Since I can control the httpcontext by there, I coded the following and it worked just fine. The page quickly stream the file to client and them close itself. Hope it helps
using (var stream = new MemoryStream())
{
using (var archive = new ZipArchive(stream, ZipArchiveMode.Create, true))
{
foreach (SPFile item in lstFiles)
{
var file = archive.CreateEntry(item.Name);
using (var entryStream = file.Open())
using (var streamWriter = new BinaryWriter(entryStream))
{
byte[] bytes = item.OpenBinary();
streamWriter.Write(bytes, 0, bytes.Length);
}
}
}
stream.Seek(0, SeekOrigin.Begin);
Byte[] byteArray = stream.ToArray();
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.CacheControl = "public";
HttpContext.Current.Response.AddHeader("Pragma", "public");
HttpContext.Current.Response.AddHeader("Expires", "0");
HttpContext.Current.Response.AddHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
HttpContext.Current.Response.AddHeader("Content-Description", "Report Export");
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=\"Anexos.zip\"");
HttpContext.Current.Response.BinaryWrite(byteArray);
HttpContext.Current.Response.Flush(); // Sends all currently buffered output to the client.
HttpContext.Current.Response.SuppressContent = true; // Gets or sets a value indicating whether to send HTTP content to the client.
HttpContext.Current.ApplicationInstance.CompleteRequest(); // Causes ASP.NET to bypass all events and filtering in the HTTP pipeline chain of execution and directly execute the EndRequest event.
}
I'm using Apache Commons IO's IOUtils.copy to make copies of existing files, on Google Cloud Storage.
Here is the problem: if the files goes beyond around 1 mb, IOUtils.copy will throw an exception. Files below 1 mb works perfectly fine.
Code snippet
AppEngineFile newFile = null;
GSFileOptionsBuilder optionsBuilder = new GSFileOptionsBuilder().setBucket("bucket-name")
.setKey(newFilename).setMimeType("image/jpeg");
try {
//currentFile is an instance of a AppEngineFile
FileReadChannel readChannel = fileService.openReadChannel(currentFile, true);
newFile = fileService.createNewGSFile(optionsBuilder.build());
FileWriteChannel writeChannel = fileService.openWriteChannel(newFile, true);
InputStream inputStream = Channels.newInputStream(readChannel);
OutputStream outputStream = Channels.newOutputStream(writeChannel);
IOUtils.copy(inputStream, outputStream);
outputStream.flush();
outputStream.close();
inputStream.close();
writeChannel.closeFinally();
} catch (IOException e) {
log.warning(e.toString());
}
I also attempted a more primitive method: but it doesn't work too
byte[] buffer = new byte[1024];
int len = inputStream.read(buffer);
while (len != -1) {
outputStream.write(buffer, 0, len);
len = inputStream.read(buffer);
}
My assumption now: there is some kind of restriction on the App Engine platform.
Note: I've also tried IOUtiles.copyLarge (which is meant for files larger than 2 GB), but it doesn't work too.
Try using a smaller than 1mb buffer. Latest appengine version reduced buffer size.
I have come across a couple of different ways to write images to isolated storage on some Windows Phone sites, however I am unsure which is the best to use for a camera app or if there are some that are better than others:
The first is from this post on a basic camera application: http://msdn.microsoft.com/en-us/library/hh202956(v=VS.92).aspx It takes the jpeg from the camera and writes it to isolated storage directly.
void cam_CaptureImageAvailable(object sender, Microsoft.Devices.ContentReadyEventArgs e)
{
string fileName = savedCounter + ".jpg";
try
{ // Write message to the UI thread.
Deployment.Current.Dispatcher.BeginInvoke(delegate()
{
txtDebug.Text = "Captured image available, saving picture.";
});
// Save picture to the library camera roll.
library.SavePictureToCameraRoll(fileName, e.ImageStream);
// Write message to the UI thread.
Deployment.Current.Dispatcher.BeginInvoke(delegate()
{
txtDebug.Text = "Picture has been saved to camera roll.";
});
// Set the position of the stream back to start
e.ImageStream.Seek(0, SeekOrigin.Begin);
// Save picture as JPEG to isolated storage.
using (IsolatedStorageFile isStore = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream targetStream = isStore.OpenFile(fileName, FileMode.Create, FileAccess.Write))
{
// Initialize the buffer for 4KB disk pages.
byte[] readBuffer = new byte[4096];
int bytesRead = -1;
// Copy the image to isolated storage.
while ((bytesRead = e.ImageStream.Read(readBuffer, 0, readBuffer.Length)) > 0)
{
targetStream.Write(readBuffer, 0, bytesRead);
}
}
}
// Write message to the UI thread.
Deployment.Current.Dispatcher.BeginInvoke(delegate()
{
txtDebug.Text = "Picture has been saved to isolated storage.";
});
}
finally
{
// Close image stream
e.ImageStream.Close();
}
}
It seems to use a 4kb Buffer, is there any point in doing it this way? Seems a bit more complicated than this method which converts the image to a bitmap then uses the save as Jpeg method (http://www.windowsphonegeek.com/tips/All-about-WP7-Isolated-Storage---Read-and-Save-Images):
// Create a filename for JPEG file in isolated storage.
String tempJPEG = "logo.jpg";
// Create virtual store and file stream. Check for duplicate tempJPEG files.
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (myIsolatedStorage.FileExists(tempJPEG))
{
myIsolatedStorage.DeleteFile(tempJPEG);
}
IsolatedStorageFileStream fileStream = myIsolatedStorage.CreateFile(tempJPEG);
StreamResourceInfo sri = null;
Uri uri = new Uri(tempJPEG, UriKind.Relative);
sri = Application.GetResourceStream(uri);
BitmapImage bitmap = new BitmapImage();
bitmap.SetSource(sri.Stream);
WriteableBitmap wb = new WriteableBitmap(bitmap);
// Encode WriteableBitmap object to a JPEG stream.
Extensions.SaveJpeg(wb, fileStream, wb.PixelWidth, wb.PixelHeight, 0, 85);
//wb.SaveJpeg(fileStream, wb.PixelWidth, wb.PixelHeight, 0, 85);
fileStream.Close();
}
If there are any alternative methods you have also I'd be interested, thanks!
Think you should check this out:
I believe I already answered this and got a +50 bounty SO Save image to Isolated Storaged using byte[]