I am trying to develop an android application using Xamarin(c#) and parse where user will capture a pic and upload it to parse. I know how to upload a text file but as I am new to this I have no idea how to deal with an image file can anyone please help. This is how I am uploading a text file
byte[] data = System.Text.Encoding.UTF8.GetBytes("This is content of the text file");
ParseFile file = new ParseFile("resume.txt", data);
await file.SaveAsync();
ParseObject gameScore = new ParseObject("GameScore");
gameScore["score"] = 0001;
gameScore["playerName"] = " Bob";
gameScore["e"] = file;
await gameScore.SaveAsync();`
Can anyone please help me with this problem.. thanks.
Parse has an entire section of docs devoted to dealing with files.
// File is in System.IO
byte[] data = File.ReadAllBytes(path_to_your_image);
ParseFile file = new ParseFile(name_of_your_file, data);
await file.SaveAsync();
// link your file object to your Parse object
gameScore["image"] = file;
Update:
The docs specifically say
It's important that you give a name to the file that has a file
extension. This lets Parse figure out the file type and handle it
accordingly. So, if you're storing PNG images, make sure your filename
ends with .png.
Related
I'm trying to export multiple Google Docs files via Google Drive API into Pdf and merge them into one using iText7 but it throws exception iText.IO.Exceptions.IOException: 'PDF header not found.' because of the weird PDF format from Google export.
Google Disk generated PDF content (read with notepad) is not valid PDF.
File content starts like this 倥䙄ㄭ㐮┊ㄊ instead of something like %PDF-1.4
The uploaded PDF file is readable from Google Disk without any problem and it is readable even if I export the Stream directly to the disk. File content is exactly the same when I download file manually through Google Docs GUI.
Here is my code to export files via API:
var mimeType = "application/pdf";
var file = GetFile(sourceFile);
var pdfRequest = _driveService.Files.Export(sourceFile, mimeType);
var stream = pdfRequest.ExecuteAsStream();
Then I'm uploading PDF back into Google Drive via it's API
var newFile = new Google.Apis.Drive.v3.Data.File();
newFile.MimeType = mimeType;
newFile.Parents = new List<string>() { targetFolder };
var createRequest = _driveService.Files.Create(newFile, stream, mimeType);
createRequest.SupportsAllDrives = true;
var createResult = createRequest.Upload();
Weirdly enough the format of exported PDF is ok when I use
var text = pdfRequest.Execute(); instead of pdfRequest.ExecuteAsStream (it starts with %PDF-1.7).
But Execute() returns string instead of Stream.
Is there any way to get standard PDF format from Google Disk API or convert it in any possible way?
The problem was in the iText7 itself. It considered PDF as invalid but it probably just does not support PDFs in iso8859_2 encoding.
I tried to use PDFSharp instead and everything went smoothly.
I've used ExecuteAsStream() from Google Disk API to get PDF Stream with no problems at all so it wasnt at fault.
Thanks for all your tips.
I have a Cordova app that uses a C# webService to communicate with a SQL database.
This works great.
My problem is that I have some pdf documents on the server with the local filePath held in the database and I need to open these in the app.
I have done a similar thing before where the documents had a URL where they could be reached so they just open, but in this case there is no external access to the file.
So my question is this....how do I best get the file from the server to the app to open it?
I don't need to store the file on the device, just open it so it can be read.
I would be really grateful if someone could steer me in the right direction as I have no clue as the best method for achieving what i'm after.
*****UPDATE******
Right, I don't think i'm a million miles away but have a feeling i'm doing something fundamentally wrong.
I'm creating a byte[] using:
byte[] bytes = System.IO.File.ReadAllBytes(filepath);
which produces a really long string.
In the app, I'm getting that string and using the following to reconstitute it as a file:
var bytes = new Uint8Array(data);
saveByteArray("mytest.txt", data);
function base64ToArrayBuffer(base64) {
var binaryString = window.atob(base64);
var binaryLen = binaryString.length;
var bytes = new Uint8Array(binaryLen);
for (var i = 0; i < binaryLen; i++) {
var ascii = binaryString.charCodeAt(i);
bytes[i] = ascii;
}
return bytes;
}
function saveByteArray(reportName, byte) {
var blob = new Blob([byte], {type: "application/txt"});
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
var fileName = reportName;
link.download = fileName;
link.click();
}
This will either create an empty file or a corrupt one.
Can anyone help with this please?
A fresh pair of eyes would be gratefully received.
Thanks
What you could do would be to make a new endpoint in your C# webservice backend, to download the file from this endpoint, to store it locally, and to display it from your app.
Behind the endpoint, it would use the file location from the database, and it would get the file content in a stream from where the pdf is stored. This stream of data would be placed in a json result object as an array of bytes. Finally, your app would have to get this json object, then to build the pdf file from the array of bytes and from the file name.
Hope it helps.
I was trying to convert .docx file to .pdf using drive api, which sounds reasonable since you can do it manually.
Here is my code:
FilesResource.CreateMediaUpload request;
using (var stream = new System.IO.FileStream(#"test.docx",
System.IO.FileMode.Open))
{
request = driveService.Files.Create(
fileMetadata, stream, "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
request.Fields = ""id, webViewLink, webContentLink, size";
var x = request.Upload();
Console.WriteLine(x);
}
var file = request.ResponseBody;
Afterwards, I am getting id of this file and trying to do:
var downloadRequest = driveService.Files.Export(file.Id, "application/pdf");
which fails with error: "Export only supports Google Docs"
Ofc! I suppose it hasn't yet become "Google DOC", however, this format is supported for conversion as mentioned here and here.
Ok, I've noticed if you go to the drive and open the file manually it will become google doc file and also will get new ID. The export on this ID will work just fine. However, doing something manually isn't acceptable approach for our needs.
Tried another approach, you can use direct link with &export=pdf parameter to convert google doc file.
https://docs.google.com/document/d/FILE_ID/export?format=doc
But passing FILEID to that link doesn't work in this case(works with "DOC" file just fine) Tried doing something similiar to stackoverflow answer. No way.
So. Is there any way to trigger File to become Google DOC and wait till it converts? Is there any other way?
Thanks in advance!
Thanks to #bash.d I was able to convert from docx to pdf.
Actually one have to use v2 of API and its "Insert" method.
https://developers.google.com/drive/v2/reference/files/insert#examples
use the code from this link and specify
request.Convert = true;
after that I used
var downloadRequest = driveService.Files.Export(file.Id, "application/pdf");
and voilà! It worked! Takes about 30 seconds to convert file in my case.
i have used below code for showing image in image picture box, now i would like add code for opening file (pdf,image,...) after reading from database
int imageID = Convert.ToInt32(imageIDComboBox.Text);
// read image bytes from the database and display in picture box
Byte[] imageByteArray = ProductDB.ReadImage(imageID);
MemoryStream ms = new MemoryStream(imageByteArray);
imagePictureBox.Image = System.Drawing.Image.FromStream(ms);
ms.Close();
i have tried to used below code but it does not recognize Response.
ms.writeto(Response.outputstream)
You need to Save the File somewhere. I suggest you use the GetTempPath method to obtain a temp file name.
after you have saved the file you can open it with the default program of the machine by using the Process class
some pseudo code:
string fileName = "C:\temp\foo.pdf"; //or use Path.GetTempPath()
ms.Write(new StreamWriter(filename)); //you may want to use a using statement for your file stream to ensure the file is closed
Process.Start(filename);
https://msdn.microsoft.com/en-us/library/system.io.path.gettemppath(v=vs.110).aspx
https://www.dotnetperls.com/process
EDIT
It seems my pseudo code does not work correctly ;-) here's another snippet:
Byte[] imageByteArray = ProductDB.ReadImage(imageID);
string fileName = Path.GetTempPath();
File.WriteAllBytes(fileName, imageByteArray);
Process.Start(fileName);
I am trying to get the content of attachment. It may be an excel file, Document file or text file whatever it is but I want to store it in database so here I am using this code: -
foreach (FileAttachment file in em.Attachments)// Here em is type of EmailMessage class
{
Console.Write("Hello friends" + file.Name);
file.Load();
var stream = new System.IO.MemoryStream(file.Content);
var reader = new System.IO.StreamReader(stream, UTF8Encoding.UTF8);
var text = reader.ReadToEnd();
reader.Close();
Console.Write("Text Document" + text);
}
So By printing file.name is showing attachment file name but while printing 'text' on the console it is working if the attachment is .txt type but if it is .doc or .xls type then it is showing some symbolic result. I am not getting any text result. Am I doing something wrong or missing something. I want text result of any kind of file attachment . Please help me , I am beginner in C#
What you are seeing is what is actually in the file. Try opening one with Notepad.
There is no built-in way in .NET to show the "text contents" of arbitrary file formats. You'll have to create (preferably using third-party libraries that already solve this problem) some kind of logic that extracts plaintext from rich text documents.
See for example How to extract text from Pdf, Word and Excel documents?, Extract text from pdf and word files, and so on.
First, what do you expect when reading a binary file?
Your result is exactly what is expected. A text file can be shown as a string, but a doc or xls file is a binary file. You will see the binary content of the file. You will need to use a tool/lib to get the text/content from a binary file in human readable format.
TXT type is simple,DOC or XLS are much more complex.You can see TXT because is just text,DOC or XLS or PPT or something else needs to be interpreted by other mechanism.
See,for example,you have different colors or font sizes on a Word document,or a chart in an Excel document,how can you show that in a simple TextBox or RichTextBox?Short answer,you can't.