Upload an image to Google Drive with OCR and convert to Doc - c#

I want to upload an image to Google Drive with OCR function and convert it to Google Doc. I am using this method
public static File UploadFile(DriveService Service, string UploadFile, string Parent)
{
if (System.IO.File.Exists(UploadFile))
{
File body = new File();
body.Title = System.IO.Path.GetFileName(UploadFile);
body.Description = "File uploaded by Diamto Drive Sample";
body.MimeType = GetMimeType(UploadFile);
body.Parents = new List<ParentReference>() { new ParentReference() { Id = Parent } };
// File’s content.
byte[] byteArray = System.IO.File.ReadAllBytes(UploadFile);
System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);
try
{
FilesResource.InsertMediaUpload request = Service.Files.Insert(body, stream, GetMimeType(UploadFile));
request.Ocr = true;
request.OcrLanguage = "he";
request.Convert = true;
return request.ResponseBody;
}
catch (Exception e)
{
Console.WriteLine("An error occurred: " + e.Message);
return null;
}
}
else
{
Console.WriteLine("File does not exist: " + UploadFile);
return null;
}
}
and I call it via this line
Google.Apis.Drive.v2.Data.File newFile = DriveHelper.UploadFile(service, #"E:\myImage.png", myFolderId);
My problem is: request.ResponseBody returns null but when I remove this lines
request.Ocr = true;
request.OcrLanguage = "he";
request.Convert = true;
My file uploaded successfully
and request.ResponseBody returns File Object

This is missing the Upload function.
request.Upload();
return request.ResponseBody;
Reference link: http://anthonygiretti.com/category/google-api/

Related

Unable to download Excel file when call from Postman

I am trying to download Excel file using web API but I am unable to download file in postman where as I am able to download Excel file when I enter URL in browser though while opening file I get warning message like below :
When i hit endpoint using POSTMAN then file get corrupted and it is showing junk characters.
Code :
protected virtual byte[] ExportToXlsx<T>(IEnumerable<T> itemsToExport)
{
using (var stream = new MemoryStream())
{
using (var xlPackage = new ExcelPackage())
{
// get handles to the worksheets
var worksheet = xlPackage.Workbook.Worksheets.Add(typeof(T).Name);
//create Headers and format them
var manager = new PropertyManager<T>(itemsToExport.First());
manager.WriteCaption(worksheet, SetCaptionStyle);
var row = 2;
foreach (var items in itemsToExport)
{
manager.CurrentObject = items;
manager.WriteToXlsx(worksheet, row++, false);
}
xlPackage.Save();
}
return stream.ToArray();
}
}
private readonly IServiceContext ctx;
public void Download(string guid)
{
var bytes = ExportToXlsx(list);
ctx.reqobj.HttpContext.Response.Headers.Add("Content-Disposition", "attachment; filename=\"demo.xlsx\"");
ctx.reqobj.HttpContext.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
ctx.reqobj.HttpContext.Response.Body.Write(bytes, 0, bytes.Length);
}
Note : I am using OfficeOpenXml for Excel file creation.
I will appreciate any help.
Update :
Try using "Send and download" instead of "Send"
https://www.getpostman.com/docs/v6/postman/sending_api_requests/responses
Postman doesn't download any file just return you the data that the server or your service provides. i have a project that download an excel to with the OpenXML here is an example with which you can guide with some styles to.
[HttpGet]
public void DownloadTable(int id)
{
List<Employee> all = db.Employees.Where(x => x.ManagerId == id).ToList();
String file = "Example.xlsx";
String path = Path.Combine(HttpContext.Current.Server.MapPath("~/App_Data"), file);
List<string[]> headerRow = new List<string[]>() { new string[] { "EmployeeId", "Name", "Shift", "Timestamp" } };
string headerRange = "A2:" + Char.ConvertFromUtf32(headerRow[0].Length + 64) + "2";
ExcelPackage excel = new ExcelPackage();
excel.Workbook.Worksheets.Add("Employees");
var page = excel.Workbook.Worksheets["Employees"];
page.Cells["A1:D1"].Merge = true;
page.Cells["A1:D1"].Value = "Supervisor: " + all.FirstOrDefault().Manager + " - " + id;
page.Cells["A1:D1"].Style.Font.Bold = true;
page.Cells[headerRange].LoadFromArrays(headerRow);
int z = 3;
foreach (Reporte r in all)
{
page.Cells["A" + z].Value = r.Id;
page.Cells["B" + z].Value = r.Name;
page.Cells["C" + z].Value = r.Shift;
page.Cells["D" + z].Value = r.Timestamp;
z++;
}
page.Cells["D3:D" + z].Style.Numberformat.Format = "dddd dd MMMM YYYY";
page.Cells["A2:D2"].AutoFilter = true;
page.Cells["A1:D" + z].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
page.Cells["A1:D" + z].Style.VerticalAlignment = ExcelVerticalAlignment.Center;
page.Cells["A2:D" + z].AutoFitColumns();
page.Cells["A1:D1"].Style.Fill.PatternType = ExcelFillStyle.Solid;
page.Cells["A1:D1"].Style.Fill.BackgroundColor.SetColor(Color.FromArgb(1, 183, 222, 232));
FileInfo excelFile = new FileInfo(path);
excel.SaveAs(excelFile);
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.ContentType = "text/plain";
response.AddHeader("Content-Disposition",
"attachment; filename=" + file + ";");
response.TransmitFile(path);
response.Flush();
response.End();
File.Delete(path);
}
The stream needs to be passed to the package.
Right now nothing is being given to the package,
//...
using (var xlPackage = new ExcelPackage())
//...
So nothing is being saved to the stream, which is why the error is shown when trying to open the file.
There is no need to convert the memory stream to an array. Return the stream and pass that along for the response.
protected virtual Stream ExportToXlsx<T>(IEnumerable<T> itemsToExport) {
var stream = new MemoryStream();
using (var xlPackage = new ExcelPackage(stream)) { //<<< pass stream
// get handles to the worksheets
var worksheet = xlPackage.Workbook.Worksheets.Add(typeof(T).Name);
//create Headers and format them
var manager = new PropertyManager<T>(itemsToExport.First());
manager.WriteCaption(worksheet, SetCaptionStyle);
var row = 2;
foreach (var items in itemsToExport) {
manager.CurrentObject = items;
manager.WriteToXlsx(worksheet, row++, false);
}
xlPackage.Save();
}
return stream;
}
A controller action to return the file would look like this
public IActionResult Download(string guid) {
//...get list
var file = ExportToXlsx(list);
var contentType = "application/vnd.openxmlformats";
var fileName = "demo.xlsx";
return File(file, contentType, fileName); //returns a FileStreamResult
}
It was indicated in comments that the above is done in a support method.
Using the same approach
private readonly IServiceContext ctx;
//...
public void Download(string guid) {
//...get list
using(var fileStream = ExportToXlsx(list)) {
if (fileStream.CanSeek && fileStream.Position != 0) {
fileStream.Seek(0, SeekOrigin.Begin);
}
var contentType = "application/vnd.openxmlformats";
var fileName = "demo.xlsx";
var response = ctx.reqobj.HttpContext.Response;
response.Headers.Add("Content-Disposition", $"attachment; filename=\"{fileName}\"");
response.Headers.Add("Content-Length", fileStream.Length.ToString());
response.ContentType = contentType;
fileStream.CopyTo(response.Body);
}
}
the generated file is copied over to the body of the response.
As for postman, the tool is simply showing the content return in the response. It does not try to download the actual file as an attachment.

Upload Excel Document From specific IP Address with multiple Sheets

I want to Upload a file from the Path given which should be a IP Address and search a Excel file there and Upload in to a Database.
The Excel File will have multiple Sheets to be Uploaded.
I also want to store different sheets in to different tables in Database.
How Can I do this in ASP.NET.
If you Are using FTP server Means write like below.The below sample is working fine with out database.
FtpWebRequest
string CompletePath = "C:/Doc/test.xlsx"; //path for file
private FtpWebRequest FTPDetail(string FileName)
{
string uri = "";
string serverIp = "255.255.255.1"; //Ftp server IP address
string Username = "test"; // Ftp User name
string Password = "test123"; // Ftp Password
uri = "ftp://" + serverIp + "/root/" + FileName;
FtpWebRequest objFTP;
objFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
objFTP.Credentials = new NetworkCredential(Username, Password);
objFTP.UsePassive = true;
objFTP.KeepAlive = false;
objFTP.Proxy = null;
objFTP.UseBinary = false;
objFTP.Timeout = 90000;
return objFTP;
}
Upload file
public bool UploadFile()
{
FtpWebRequest objFTP= null;
try
{
objFTP= FTPDetail("File.xlsx");
objFTP.Method = WebRequestMethods.Ftp.UploadFile;
using (FileStream fs = File.OpenRead(CompletePath))
{
byte[] buff = new byte[fs.Length];
using (Stream strm = objFTP.GetRequestStream())
{
contentLen = fs.Read(buff, 0, buff.Length);
while (contentLen != 0)
{
strm.Write(buff, 0, buff.Length);
contentLen = fs.Read(buff, 0, buff.Length);
}
objFTP = null;
}
}
return true;
}
catch (Exception Ex)
{
if (objFTP!= null)
{
objFTP.Abort();
}
throw Ex;
}
}

How to upload image on amzon s3 using .net web api c#?

I have create one api for the image upload. in this code i have upload time image download in my local folder and store. but i need now change my code and move this image download on amzon s3. i have found one link in searching time but in this link static image is upload i need image browse from the file upload control and download on amzon server. but how can do that i have no idea. please any one how can do that then please help me. here below listed my code. and also add i have try this code in below.
this is my api method for the image upload :
[HttpPost]
[Route("FileUpload")]
public HttpResponseMessage FileUpload(string FileUploadType)
{
try
{
var httpRequest = HttpContext.Current.Request;
if (httpRequest.Files.Count > 0)
{
foreach (string file in httpRequest.Files)
{
var postedFile = httpRequest.Files[file];
string fname = System.IO.Path.GetFileNameWithoutExtension(postedFile.FileName.ToString());
string extension = Path.GetExtension(postedFile.FileName);
Image img = null;
string newFileName = "";
newFileName = DateTime.Now.ToString("yyyyMMddhhmmssfff") + ".jpeg";
string path = ConfigurationManager.AppSettings["ImageUploadPath"].ToString();
string filePath = Path.Combine(path, newFileName);
SaveJpg(img, filePath);
return Request.CreateResponse(HttpStatusCode.OK, "Ok");
}
}
}
catch (Exception ex)
{
return ex;
}
return Request.CreateResponse(HttpStatusCode.OK, "Ok");
}
This is my save image api =>
public static void SaveJpg(Image image, string file_name, long compression = 60)
{
try
{
EncoderParameters encoder_params = new EncoderParameters(1);
encoder_params.Param[0] = new EncoderParameter(
System.Drawing.Imaging.Encoder.Quality, compression);
ImageCodecInfo image_codec_info =
GetEncoderInfo("image/jpeg");
image.Save(file_name, image_codec_info, encoder_params);
}
catch (Exception ex)
{
}
}
i have try this code with static image upload on server =>
private string bucketName = "Xyz";
private string keyName = "abc.jpeg";
private string filePath = "C:\\Users\\I BALL\\Desktop\\image\\abc.jpeg";. // this image is store on server
public void UploadFile()
{
var client = new AmazonS3Client(Amazon.RegionEndpoint.USEast1);
try
{
PutObjectRequest putRequest = new PutObjectRequest
{
BucketName = bucketName,
Key = keyName,
FilePath = filePath,
ContentType = "text/plain"
};
PutObjectResponse response = client.PutObject(putRequest);
}
catch (AmazonS3Exception amazonS3Exception)
{
if (amazonS3Exception.ErrorCode != null &&
(amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId")
||
amazonS3Exception.ErrorCode.Equals("InvalidSecurity")))
{
throw new Exception("Check the provided AWS Credentials.");
}
else
{
throw new Exception("Error occurred: " + amazonS3Exception.Message);
}
}
}
here i have show my code but i need to marge with my code so how can do that please any one know how can do that.
This might be too late, but here is how I did it:
Short Answer: Amazon S3 SDK for .Net has a class called "TransferUtility" which accepts a Stream object, so as long as you can convert your file to any Class derived from the abstract Stream class, you can upload the file.
Long Answer:
The httprequest posted files has an inputStream property, so inside your foreach loop:
var postedFile = httpRequest.Files[file];
If you expand on this object, it is of type "HttpPostedFile", so you have access to the Stream through the InputStream property:
Here is some snippets from a working sample:
//get values from the headers
HttpPostedFile postedFile = httpRequest.Files["File"];
//convert the posted file stream a to memory stream
System.IO.MemoryStream target = new System.IO.MemoryStream();
postedFile.InputStream.CopyTo(target);
//the following static function is a function I built which accepts the amazon file key and also the object that will be uploaded to S3, in this case, a MemoryStream object
s3.WritingAnObject(fileKey, target);
The S3 is an instance of a class called "S3Uploader", here are some snippets that can get you going,
below are some needed namespaces:
using Amazon;
using Amazon.Runtime;
using Amazon.S3;
using Amazon.S3.Model;
using Amazon.S3.Transfer;
class constructor:
static IAmazonS3 client;
static TransferUtility fileTransferUtility;
public S3Uploader(string accessKeyId, string secretAccessKey,string bucketName)
{
_bucketName = bucketName;
var credentials = new BasicAWSCredentials(accessKeyId, secretAccessKey);
client = new AmazonS3Client(credentials, RegionEndpoint.USEast1);
fileTransferUtility = new TransferUtility(client);
}
Notice here that we are creating the credentials using the BasicAWSCredentials class instead of passing it to the AmazonS3Client directly. And then we are using fileTransferUtility class to have better control over what is sent to S3. and here is how the Upload works based on Memory Stream:
public void WritingAnObject(string keyName, MemoryStream fileToUpload)
{
try
{
TransferUtilityUploadRequest fileTransferUtilityRequest = new
TransferUtilityUploadRequest
{
StorageClass = S3StorageClass.ReducedRedundancy,
CannedACL = S3CannedACL.Private
};
fileTransferUtility.Upload(fileToUpload, _bucketName, keyName);
}
catch (AmazonS3Exception amazonS3Exception)
{
//your error handling here
}
}
Hope this helps someone with similar issues.

Google Drive Parse error when uploading file with special unicode characters

A problem has occurred recently when trying to upload files with the Google API dotnet client sdk. When the file name has any special Unicode characters, it throws an error.
Here is my code
public static Google.Apis.Drive.v2.Data.File InsertResource(Google.Apis.Drive.v2.DriveService service, string filePath, string parentId, string fileName, string mimeType)
{
Google.Apis.Drive.v2.Data.File body = new Google.Apis.Drive.v2.Data.File();
try
{
// File's metadata.
body.Title = fileName;
body.MimeType = mimeType;
// Set the parent folder.
if (!String.IsNullOrEmpty(parentId))
{
var response = DriveUtils.GetFileInfo(service, parentId);
if (response.Error != null)
{
body.Error = response.Error;
return body;
}
body.Parents = new List<ParentReference>() { new ParentReference() { Id = parentId } };
}
byte[] byteArray = System.IO.File.ReadAllBytes(filePath);
MemoryStream stream = new MemoryStream(byteArray);
Google.Apis.Drive.v2.FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, mimeType);
request.Upload();
return request.ResponseBody;
}
catch (GoogleApiRequestException e)
{
body.Error = e.RequestError;
return body;
}
}
It was working fine up until this week. Any files that have chinese characters or turkish characters in the name will throw an error.
at Google.Apis.Json.JsonReader.ParseExpression(JsonToken token, TokenStream ts)
at Google.Apis.Json.JsonReader.Parse(String jsonAsText)
at Google.Apis.Upload.ResumableUpload`1.Upload()
Try to download the latest version of the API (from https://code.google.com/p/google-api-dotnet-client/wiki/APIs#Drive_API).
I changed line 122 in the Drive sample (instructions to download this sample are here), to
Title = "字/漢字" and Title = "title with ç", and both of them worked for me.

ASP.NET Image Upload Parameter Not Valid. Exception

Im just trying to save a file to disk using a posted stream from jquery uploadify
I'm also getting Parameter not valid.
On adding to the error message so i can tell where it blew up in production im seeing it blow up on:
var postedBitmap = new Bitmap(postedFileStream)
any help would be most appreciated
public string SaveImageFile(Stream postedFileStream, string fileDirectory, string fileName, int imageWidth, int imageHeight)
{
string result = "";
string fullFilePath = Path.Combine(fileDirectory, fileName);
string exhelp = "";
if (!File.Exists(fullFilePath))
{
try
{
using (var postedBitmap = new Bitmap(postedFileStream))
{
exhelp += "got past bmp creation" + fullFilePath;
using (var imageToSave = ImageHandler.ResizeImage(postedBitmap, imageWidth, imageHeight))
{
exhelp += "got past resize";
if (!Directory.Exists(fileDirectory))
{
Directory.CreateDirectory(fileDirectory);
}
result = "Success";
postedBitmap.Dispose();
imageToSave.Save(fullFilePath, GetImageFormatForFile(fileName));
}
exhelp += "got past save";
}
}
catch (Exception ex)
{
result = "Save Image File Failed " + ex.Message + ex.StackTrace;
Global.SendExceptionEmail("Save Image File Failed " + exhelp, ex);
}
}
return result;
}
Use image converter to load from byte array:
ImageConverter imageConverter = new System.Drawing.ImageConverter();
Image image = imageConverter.ConvertFrom(byteArray) as Image;
http://forums.asp.net/t/1109959.aspx
It seems your stream type is not valid for Bitmap object, try to copy stream to MemoryStream, and give MemoryStream as a parameter of Bitmap
and remove second dispose as #Aliostad mentoined
something like this
public string SaveImageFile(Stream postedFileStream, string fileDirectory, string fileName, int imageWidth, int imageHeight)
{
string result = "";
string fullFilePath = Path.Combine(fileDirectory, fileName);
string exhelp = "";
if (!File.Exists(fullFilePath))
{
try
{
using(var memoryStream = new MemoryStream())
{
postedFileStream.CopyTo(memoryStream);
memoryStream.Position = 0;
using (var postedBitmap = new Bitmap(memoryStream))
{
.........
}
}
}
catch (Exception ex)
{
result = "Save Image File Failed " + ex.Message + ex.StackTrace;
Global.SendExceptionEmail("Save Image File Failed " + exhelp, ex);
}
}
return result;
}

Categories