Create and saving file in published ASP.Net Core API not working
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}
I am trying to make .Net Core API that convert an uploaded file to pdf using google drive API (docx, excel, etc) and iTextSharp (png, jpeg, etc). First i upload the file to the server and it's saved on the server directories, then i take that file to be converted to PDF (using Drive API or iTextSharp) and saved to the same folder but it's not working and there's no error. When i tested it in the localhost, it working just fine. Here's the code :
public async System.Threading.Tasks.Task DriveExcelAsync(string pathupload, string download, string filename, string ext)
{
// UserCredential credential;
string serviceAccountEmail = "myaccount@myaccount-api.im.gserviceaccount.com";
var certificate = new X509Certificate2(Path.Combine(Directory.GetCurrentDirectory(), "key.p12"), "secret", X509KeyStorageFlags.Exportable);
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = new { DriveService.Scope.Drive }
}.FromCertificate(certificate));
// Create Drive API service.
var service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
string mime = "";
string reqstream = "";
if (ext == ".xls" || ext == ".xlsx")
{
mime = "application/vnd.google-apps.spreadsheet";
reqstream = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
}
else if (ext == ".doc" || ext == ".docx")
{
mime = "application/vnd.google-apps.document";
reqstream = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
}
var fileMetadata = new Google.Apis.Drive.v3.Data.File()
{
Name = filename,
MimeType = mime
};
FilesResource.CreateMediaUpload request;
using (var stream1 = new System.IO.FileStream(pathupload,
System.IO.FileMode.Open))
{
request = service.Files.Create(
fileMetadata, stream1, reqstream);
request.Fields = "id";
request.Upload();
request.Resume();
}
var file = request.ResponseBody;
Console.WriteLine("File ID: " + file.Id);
//DOWNLOAD FILE
var fileId = file.Id;
var request1 = service.Files.Export(fileId, "application/pdf");
var streamdownload = new System.IO.MemoryStream();
request1.MediaDownloader.ProgressChanged +=
(IDownloadProgress progress) =>
{
switch (progress.Status)
{
case DownloadStatus.Downloading:
{
Console.WriteLine(progress.BytesDownloaded);
break;
}
case DownloadStatus.Completed:
{
Console.WriteLine("Download complete.");
using (FileStream fileOutp = new FileStream(download, FileMode.Create, FileAccess.Write))
{
streamdownload.WriteTo(fileOutp);
}
break;
}
case DownloadStatus.Failed:
{
Console.WriteLine("Download failed.");
break;
}
}
};
request1.Download(streamdownload);
}
public async void ConvertToPdf(string filePath, string filename)
{
string ext = Path.GetExtension(filePath).ToLower();
object paramSourcePath = filePath;
object paramMissing = Type.Missing;
string paramExportFilePath = Path.Combine(Directory.GetCurrentDirectory(), "File", filename + ".pdf");
try
{
await DriveExcelAsync(filePath, paramExportFilePath, filename, ext);
if (ext == ".doc" || ext == ".docx" || ext == ".xls" || ext == ".xlsx")
{
await DriveExcelAsync(filePath, paramExportFilePath, filename, ext);
}
else if (ext == ".jpg" || ext == ".jpeg" || ext == ".png")
{
iTextSharp.text.Rectangle pageSize = null;
using (var srcImage = new Bitmap(filePath))
{
pageSize = new iTextSharp.text.Rectangle(0, 0, srcImage.Width, srcImage.Height);
}
using (var ms = new MemoryStream())
{
var document = new iTextSharp.text.Document(pageSize, 0, 0, 0, 0);
PdfWriter.GetInstance(document, ms).SetFullCompression();
document.Open();
var image = iTextSharp.text.Image.GetInstance(filePath);
document.Add(image);
document.Close();
System.IO.File.WriteAllBytes(paramExportFilePath, ms.ToArray());
}
}
}catch(Exception e)
{
throw e;
}
}
i think the part that should be saving the converted file is not working for some reason after i publish the project. Anyone know how to solve this? thanks.
UPDATE
After trying many thing, i can finally make it work by moving the published project to another domain/sites which is using different IIS app pool identity. But i still doesn't know why it's not working on the previous domain/sites, i think it is related with IIS app pool identity permission.
c# iis asp.net-core google-drive-sdk asp.net-core-webapi
add a comment |
I am trying to make .Net Core API that convert an uploaded file to pdf using google drive API (docx, excel, etc) and iTextSharp (png, jpeg, etc). First i upload the file to the server and it's saved on the server directories, then i take that file to be converted to PDF (using Drive API or iTextSharp) and saved to the same folder but it's not working and there's no error. When i tested it in the localhost, it working just fine. Here's the code :
public async System.Threading.Tasks.Task DriveExcelAsync(string pathupload, string download, string filename, string ext)
{
// UserCredential credential;
string serviceAccountEmail = "myaccount@myaccount-api.im.gserviceaccount.com";
var certificate = new X509Certificate2(Path.Combine(Directory.GetCurrentDirectory(), "key.p12"), "secret", X509KeyStorageFlags.Exportable);
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = new { DriveService.Scope.Drive }
}.FromCertificate(certificate));
// Create Drive API service.
var service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
string mime = "";
string reqstream = "";
if (ext == ".xls" || ext == ".xlsx")
{
mime = "application/vnd.google-apps.spreadsheet";
reqstream = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
}
else if (ext == ".doc" || ext == ".docx")
{
mime = "application/vnd.google-apps.document";
reqstream = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
}
var fileMetadata = new Google.Apis.Drive.v3.Data.File()
{
Name = filename,
MimeType = mime
};
FilesResource.CreateMediaUpload request;
using (var stream1 = new System.IO.FileStream(pathupload,
System.IO.FileMode.Open))
{
request = service.Files.Create(
fileMetadata, stream1, reqstream);
request.Fields = "id";
request.Upload();
request.Resume();
}
var file = request.ResponseBody;
Console.WriteLine("File ID: " + file.Id);
//DOWNLOAD FILE
var fileId = file.Id;
var request1 = service.Files.Export(fileId, "application/pdf");
var streamdownload = new System.IO.MemoryStream();
request1.MediaDownloader.ProgressChanged +=
(IDownloadProgress progress) =>
{
switch (progress.Status)
{
case DownloadStatus.Downloading:
{
Console.WriteLine(progress.BytesDownloaded);
break;
}
case DownloadStatus.Completed:
{
Console.WriteLine("Download complete.");
using (FileStream fileOutp = new FileStream(download, FileMode.Create, FileAccess.Write))
{
streamdownload.WriteTo(fileOutp);
}
break;
}
case DownloadStatus.Failed:
{
Console.WriteLine("Download failed.");
break;
}
}
};
request1.Download(streamdownload);
}
public async void ConvertToPdf(string filePath, string filename)
{
string ext = Path.GetExtension(filePath).ToLower();
object paramSourcePath = filePath;
object paramMissing = Type.Missing;
string paramExportFilePath = Path.Combine(Directory.GetCurrentDirectory(), "File", filename + ".pdf");
try
{
await DriveExcelAsync(filePath, paramExportFilePath, filename, ext);
if (ext == ".doc" || ext == ".docx" || ext == ".xls" || ext == ".xlsx")
{
await DriveExcelAsync(filePath, paramExportFilePath, filename, ext);
}
else if (ext == ".jpg" || ext == ".jpeg" || ext == ".png")
{
iTextSharp.text.Rectangle pageSize = null;
using (var srcImage = new Bitmap(filePath))
{
pageSize = new iTextSharp.text.Rectangle(0, 0, srcImage.Width, srcImage.Height);
}
using (var ms = new MemoryStream())
{
var document = new iTextSharp.text.Document(pageSize, 0, 0, 0, 0);
PdfWriter.GetInstance(document, ms).SetFullCompression();
document.Open();
var image = iTextSharp.text.Image.GetInstance(filePath);
document.Add(image);
document.Close();
System.IO.File.WriteAllBytes(paramExportFilePath, ms.ToArray());
}
}
}catch(Exception e)
{
throw e;
}
}
i think the part that should be saving the converted file is not working for some reason after i publish the project. Anyone know how to solve this? thanks.
UPDATE
After trying many thing, i can finally make it work by moving the published project to another domain/sites which is using different IIS app pool identity. But i still doesn't know why it's not working on the previous domain/sites, i think it is related with IIS app pool identity permission.
c# iis asp.net-core google-drive-sdk asp.net-core-webapi
Have you tried testing it with Local IIS on your machine (not the VS IIS Express)?
– Anton Toshik
Jan 3 at 10:43
i just test it on local IIS, and it is working fine
– Sandy Rizky
Jan 4 at 2:58
add a comment |
I am trying to make .Net Core API that convert an uploaded file to pdf using google drive API (docx, excel, etc) and iTextSharp (png, jpeg, etc). First i upload the file to the server and it's saved on the server directories, then i take that file to be converted to PDF (using Drive API or iTextSharp) and saved to the same folder but it's not working and there's no error. When i tested it in the localhost, it working just fine. Here's the code :
public async System.Threading.Tasks.Task DriveExcelAsync(string pathupload, string download, string filename, string ext)
{
// UserCredential credential;
string serviceAccountEmail = "myaccount@myaccount-api.im.gserviceaccount.com";
var certificate = new X509Certificate2(Path.Combine(Directory.GetCurrentDirectory(), "key.p12"), "secret", X509KeyStorageFlags.Exportable);
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = new { DriveService.Scope.Drive }
}.FromCertificate(certificate));
// Create Drive API service.
var service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
string mime = "";
string reqstream = "";
if (ext == ".xls" || ext == ".xlsx")
{
mime = "application/vnd.google-apps.spreadsheet";
reqstream = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
}
else if (ext == ".doc" || ext == ".docx")
{
mime = "application/vnd.google-apps.document";
reqstream = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
}
var fileMetadata = new Google.Apis.Drive.v3.Data.File()
{
Name = filename,
MimeType = mime
};
FilesResource.CreateMediaUpload request;
using (var stream1 = new System.IO.FileStream(pathupload,
System.IO.FileMode.Open))
{
request = service.Files.Create(
fileMetadata, stream1, reqstream);
request.Fields = "id";
request.Upload();
request.Resume();
}
var file = request.ResponseBody;
Console.WriteLine("File ID: " + file.Id);
//DOWNLOAD FILE
var fileId = file.Id;
var request1 = service.Files.Export(fileId, "application/pdf");
var streamdownload = new System.IO.MemoryStream();
request1.MediaDownloader.ProgressChanged +=
(IDownloadProgress progress) =>
{
switch (progress.Status)
{
case DownloadStatus.Downloading:
{
Console.WriteLine(progress.BytesDownloaded);
break;
}
case DownloadStatus.Completed:
{
Console.WriteLine("Download complete.");
using (FileStream fileOutp = new FileStream(download, FileMode.Create, FileAccess.Write))
{
streamdownload.WriteTo(fileOutp);
}
break;
}
case DownloadStatus.Failed:
{
Console.WriteLine("Download failed.");
break;
}
}
};
request1.Download(streamdownload);
}
public async void ConvertToPdf(string filePath, string filename)
{
string ext = Path.GetExtension(filePath).ToLower();
object paramSourcePath = filePath;
object paramMissing = Type.Missing;
string paramExportFilePath = Path.Combine(Directory.GetCurrentDirectory(), "File", filename + ".pdf");
try
{
await DriveExcelAsync(filePath, paramExportFilePath, filename, ext);
if (ext == ".doc" || ext == ".docx" || ext == ".xls" || ext == ".xlsx")
{
await DriveExcelAsync(filePath, paramExportFilePath, filename, ext);
}
else if (ext == ".jpg" || ext == ".jpeg" || ext == ".png")
{
iTextSharp.text.Rectangle pageSize = null;
using (var srcImage = new Bitmap(filePath))
{
pageSize = new iTextSharp.text.Rectangle(0, 0, srcImage.Width, srcImage.Height);
}
using (var ms = new MemoryStream())
{
var document = new iTextSharp.text.Document(pageSize, 0, 0, 0, 0);
PdfWriter.GetInstance(document, ms).SetFullCompression();
document.Open();
var image = iTextSharp.text.Image.GetInstance(filePath);
document.Add(image);
document.Close();
System.IO.File.WriteAllBytes(paramExportFilePath, ms.ToArray());
}
}
}catch(Exception e)
{
throw e;
}
}
i think the part that should be saving the converted file is not working for some reason after i publish the project. Anyone know how to solve this? thanks.
UPDATE
After trying many thing, i can finally make it work by moving the published project to another domain/sites which is using different IIS app pool identity. But i still doesn't know why it's not working on the previous domain/sites, i think it is related with IIS app pool identity permission.
c# iis asp.net-core google-drive-sdk asp.net-core-webapi
I am trying to make .Net Core API that convert an uploaded file to pdf using google drive API (docx, excel, etc) and iTextSharp (png, jpeg, etc). First i upload the file to the server and it's saved on the server directories, then i take that file to be converted to PDF (using Drive API or iTextSharp) and saved to the same folder but it's not working and there's no error. When i tested it in the localhost, it working just fine. Here's the code :
public async System.Threading.Tasks.Task DriveExcelAsync(string pathupload, string download, string filename, string ext)
{
// UserCredential credential;
string serviceAccountEmail = "myaccount@myaccount-api.im.gserviceaccount.com";
var certificate = new X509Certificate2(Path.Combine(Directory.GetCurrentDirectory(), "key.p12"), "secret", X509KeyStorageFlags.Exportable);
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = new { DriveService.Scope.Drive }
}.FromCertificate(certificate));
// Create Drive API service.
var service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
string mime = "";
string reqstream = "";
if (ext == ".xls" || ext == ".xlsx")
{
mime = "application/vnd.google-apps.spreadsheet";
reqstream = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
}
else if (ext == ".doc" || ext == ".docx")
{
mime = "application/vnd.google-apps.document";
reqstream = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
}
var fileMetadata = new Google.Apis.Drive.v3.Data.File()
{
Name = filename,
MimeType = mime
};
FilesResource.CreateMediaUpload request;
using (var stream1 = new System.IO.FileStream(pathupload,
System.IO.FileMode.Open))
{
request = service.Files.Create(
fileMetadata, stream1, reqstream);
request.Fields = "id";
request.Upload();
request.Resume();
}
var file = request.ResponseBody;
Console.WriteLine("File ID: " + file.Id);
//DOWNLOAD FILE
var fileId = file.Id;
var request1 = service.Files.Export(fileId, "application/pdf");
var streamdownload = new System.IO.MemoryStream();
request1.MediaDownloader.ProgressChanged +=
(IDownloadProgress progress) =>
{
switch (progress.Status)
{
case DownloadStatus.Downloading:
{
Console.WriteLine(progress.BytesDownloaded);
break;
}
case DownloadStatus.Completed:
{
Console.WriteLine("Download complete.");
using (FileStream fileOutp = new FileStream(download, FileMode.Create, FileAccess.Write))
{
streamdownload.WriteTo(fileOutp);
}
break;
}
case DownloadStatus.Failed:
{
Console.WriteLine("Download failed.");
break;
}
}
};
request1.Download(streamdownload);
}
public async void ConvertToPdf(string filePath, string filename)
{
string ext = Path.GetExtension(filePath).ToLower();
object paramSourcePath = filePath;
object paramMissing = Type.Missing;
string paramExportFilePath = Path.Combine(Directory.GetCurrentDirectory(), "File", filename + ".pdf");
try
{
await DriveExcelAsync(filePath, paramExportFilePath, filename, ext);
if (ext == ".doc" || ext == ".docx" || ext == ".xls" || ext == ".xlsx")
{
await DriveExcelAsync(filePath, paramExportFilePath, filename, ext);
}
else if (ext == ".jpg" || ext == ".jpeg" || ext == ".png")
{
iTextSharp.text.Rectangle pageSize = null;
using (var srcImage = new Bitmap(filePath))
{
pageSize = new iTextSharp.text.Rectangle(0, 0, srcImage.Width, srcImage.Height);
}
using (var ms = new MemoryStream())
{
var document = new iTextSharp.text.Document(pageSize, 0, 0, 0, 0);
PdfWriter.GetInstance(document, ms).SetFullCompression();
document.Open();
var image = iTextSharp.text.Image.GetInstance(filePath);
document.Add(image);
document.Close();
System.IO.File.WriteAllBytes(paramExportFilePath, ms.ToArray());
}
}
}catch(Exception e)
{
throw e;
}
}
i think the part that should be saving the converted file is not working for some reason after i publish the project. Anyone know how to solve this? thanks.
UPDATE
After trying many thing, i can finally make it work by moving the published project to another domain/sites which is using different IIS app pool identity. But i still doesn't know why it's not working on the previous domain/sites, i think it is related with IIS app pool identity permission.
c# iis asp.net-core google-drive-sdk asp.net-core-webapi
c# iis asp.net-core google-drive-sdk asp.net-core-webapi
edited Jan 4 at 8:17
Sandy Rizky
asked Jan 3 at 7:21


Sandy RizkySandy Rizky
458
458
Have you tried testing it with Local IIS on your machine (not the VS IIS Express)?
– Anton Toshik
Jan 3 at 10:43
i just test it on local IIS, and it is working fine
– Sandy Rizky
Jan 4 at 2:58
add a comment |
Have you tried testing it with Local IIS on your machine (not the VS IIS Express)?
– Anton Toshik
Jan 3 at 10:43
i just test it on local IIS, and it is working fine
– Sandy Rizky
Jan 4 at 2:58
Have you tried testing it with Local IIS on your machine (not the VS IIS Express)?
– Anton Toshik
Jan 3 at 10:43
Have you tried testing it with Local IIS on your machine (not the VS IIS Express)?
– Anton Toshik
Jan 3 at 10:43
i just test it on local IIS, and it is working fine
– Sandy Rizky
Jan 4 at 2:58
i just test it on local IIS, and it is working fine
– Sandy Rizky
Jan 4 at 2:58
add a comment |
0
active
oldest
votes
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54017951%2fcreate-and-saving-file-in-published-asp-net-core-api-not-working%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
0
active
oldest
votes
0
active
oldest
votes
active
oldest
votes
active
oldest
votes
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54017951%2fcreate-and-saving-file-in-published-asp-net-core-api-not-working%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Have you tried testing it with Local IIS on your machine (not the VS IIS Express)?
– Anton Toshik
Jan 3 at 10:43
i just test it on local IIS, and it is working fine
– Sandy Rizky
Jan 4 at 2:58