i want to download file in zip,but i got error my code and regarding error are bellow
My code:
using (ZipFile zip = new ZipFile())
{
zip.AlternateEncodingUsage = ZipOption.AsNecessary;
zip.AddDirectoryByName("Files");
//foreach (GridViewRow row in GridView1.Rows)
//{
// if ((row.FindControl("chkSelect") as CheckBox).Checked)
// {
// string filePath = (row.FindControl("lblFilePath") as Label).Text;
// zip.AddFile(filePath, "Files");
// }
//}
DirectoryInfo directory = new DirectoryInfo(Server.MapPath(#"~\Election\Latur"));
var files = directory.GetFiles().ToList();
foreach (var file in files)
{
zip.AddFile(file.ToString(),"Files");
}
Response.Clear();
Response.BufferOutput = false;
string zipName = String.Format("Zip_{0}.zip", DateTime.Now.ToString("yyyy-MMM-dd-HHmmss"));
Response.ContentType = "application/zip";
Response.AddHeader("content-disposition", "attachment; filename=" + zipName);
zip.Save(Response.OutputStream);
Response.End();
}
when am using above code for download file in zip then follwing error occure
error
There are two possible cause of this error:
1- The directory "Files" not possible create(denied permission)
2- Not possible obtain files into "~\Election\Latur"
Anyway the lines:
var files = directory.GetFiles().ToList();
foreach (var file in files)
The type var i think is not correct for this. String with base64 coder is more correct.
using (ZipFile zip = new ZipFile())
{
string folderpath = Server.MapPath(#"~\Election\Latur\");
zip.AlternateEncodingUsage = ZipOption.AsNecessary;
zip.AddDirectoryByName("Files");
DirectoryInfo directory = new DirectoryInfo(Server.MapPath(#"~\Election\Latur"));
var files = directory.GetFiles().ToList();
foreach (var file in files)
{
var filepath = folderpath + file.ToString();
zip.AddFile(filepath,"Files");
}
Response.Clear();
Response.BufferOutput = false;
string zipName = String.Format("Zip_{0}.zip", DateTime.Now.ToString("yyyy-MMM-dd-HHmmss"));
Response.ContentType = "application/zip";
Response.AddHeader("content-disposition", "attachment; filename=" + zipName);
zip.Save(Response.OutputStream);
Response.End();
}
Related
I have tried the following code ..
When I try out the following code I get 404 content not found. Also my controller doesn't get hit when I try to debug the code ..
public async Task<IActionResult> Download(string filename)
{
if (filename == null)
return Content("filename not present");
var path = Path.Combine(Directory.GetCurrentDirectory(),"wwwroot", filename);
var memory = new MemoryStream();
using (var stream = new FileStream(path, FileMode.Open))
{
await stream.CopyToAsync(memory);
}
memory.Position = 0;
return File(memory, GetContentType(path), Path.GetFileName(path));
}
Upload file with size and filename as response:
public async Task<IActionResult> OnPostUploadAsync(IFormFile file)
{
long size = file.Length;//in bytes
if (file.Length > 0)
{
var name = Path.GetRandomFileName();
//var fileOriginName = file.FileName;
var path = Path.Combine(System.IO.Directory.GetCurrentDirectory(), "wwwroot", name);
using (var stream = System.IO.File.Create(path))
{
await file.CopyToAsync(stream);
}
return Ok(new { size = size, filename = name });
}
else {
return Ok(new { size = 0, filename = ""});
}
}
===============================================
I have an api like below and I had a file test.txt in wwwroot folder.
public async Task<IActionResult> Download(string filename)
{
if (filename == null)
return Content("filename not present");
var path = Path.Combine(System.IO.Directory.GetCurrentDirectory(), "wwwroot", filename);
var memory = new MemoryStream();
using (var stream = new FileStream(path, FileMode.Open))
{
await stream.CopyToAsync(memory);
}
memory.Position = 0;
var contentType = "APPLICATION/octet-stream";
return File(memory, contentType, Path.GetFileName(path));
}
Then when I call localhost:port/home/download?filename=test then I'll get exception that file can't find. And when I call localhost:port/home/Download?filename=test.txt it succeeds.
My API is in an asp.net core MVC project and I think you need to check the contentType.
I am new to .net core and c#. I have a file upload requirement in my project. I am trying to upload my file to aws s3. I upload file from a folder in my project root folder and then delete the uploaded file from there. But when I try to upload to s3 I am getting following error
The process cannot access the file because it is being used by another process.
Here is my code to upload file
string fileFolder = Path.Combine(hostingEnvironment.WebRootPath, "TempFiles");
uniqueFileName1 = Guid.NewGuid().ToString() + "_" + cm.UDocument1.FileName;
string filePath = Path.Combine(fileFolder, uniqueFileName1);
cm.UDocument1.CopyTo(new FileStream(filePath, FileMode.Create));
var tempPath = Path.Combine(hostingEnvironment.WebRootPath, "TempFiles", Path.GetFileName(uniqueFileName1));
UploadFile(cm.UDocument1,tempPath);
[HttpPost]
public ActionResult UploadFile(IFormFile file,string path)
{
var s3Client = new AmazonS3Client(accesskey, secretkey, bucketRegion);
var fileTransferUtility = new TransferUtility(s3Client);
try
{
if (file.Length > 0)
{
var fileTransferUtilityRequest = new TransferUtilityUploadRequest
{
BucketName = bucketName,
FilePath = path,
StorageClass = S3StorageClass.Standard,
Key = file.FileName
};
fileTransferUtilityRequest.Metadata.Add("param1", "Value1");
fileTransferUtilityRequest.Metadata.Add("param2", "Value2");
fileTransferUtility.Upload(fileTransferUtilityRequest);
fileTransferUtility.Dispose();
string[] tmp = { "" };
tmp = fileName.Split("-");
}
ViewBag.Message = "File Uploaded Successfully!!";
if (System.IO.File.Exists(path))
{
System.IO.File.Delete(path);
}
}
return ViewBag.Message;
}
what can I do about it?
On this line:
cm.UDocument1.CopyTo(new FileStream(filePath, FileMode.Create));
You create a file stream but you dont dispose it.
wrap in a using statement instead:
using (var iNeedToLearnAboutDispose = new FileStream(filePath, FileMode.Create))
{
cm.UDocument1.CopyTo(iNeedToLearnAboutDispose);
}
This is my code..
[HttpPost]
public ActionResult Export()
{
GridView grid = new GridView();
StringWriter sw = new StringWriter();
var ItemsFromDb = lst.FetchDataFromList(Session["userId"].ToString()).ToList();
if (ItemsFromDb.Count != 0)
{
grid.DataSource = ItemsFromDb;
grid.DataBind();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("Content-disposition", "Attachment;filename=" + "Members_" + DateTime.Now.ToString("dd/mm/yyy") + ".pdf");
Response.ContentType = "application/pdf";
Response.Charset = "";
HtmlTextWriter hw = new HtmlTextWriter(sw);
grid.RenderControl(hw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
else
{
TempData["Message"] = "Sorry.. No data to export.";
return View();
}
return RedirectToAction("UserDetails","EmployeeLocation");
}
This code works perfectly fine for creating and downloading excel format by only changing the types as .xls and "application/ms-excel"
but the is side the pdf the datas are not loading...
i've created a function that creates a pdf file and insert it into a doc file, problem is i can't download it from that directory, here is my code:
private void FillForm(Dictionary<string, string> dic)
{
var pdfTemplate = HttpContext.Current.Server.MapPath("~/ress/NOUVELLE_VERSION_GENE_15_04_2014.pdf"); //_pdfTemplet;
var newFile = _newFileName + "_" + Guid.NewGuid() + ".pdf";
_gNewFile = newFile.ToString();
var pdfReader = new PdfReader(System.IO.File.ReadAllBytes(pdfTemplate));
var pfileStream = new FileStream(string.Format(HttpContext.Current.Server.MapPath("~/ress/") + "{0}", newFile), FileMode.Create);
var pdfStamper = new PdfStamper(pdfReader, pfileStream);
var pdfFormFields = pdfStamper.AcroFields;
foreach (var entry in dic)
{
pdfFormFields.SetField(entry.Key, entry.Value);
}
pdfStamper.FormFlattening = true;
pdfStamper.JavaScript = "this.print(true);\r";
pdfStamper.Writer.CloseStream = false;
pdfReader.Close();
pdfStamper.Close();
UPContract.Update();
pfileStream.Close();
pdf.FilePath = string.Format("../Ress/{0}", Path.GetFileName(_gNewFile));
Response.Clear();
byte[] bytes = System.IO.File.ReadAllBytes(string.Format(HttpContext.Current.Server.MapPath("~/ress/") + "{0}", _gNewFile));
Response.ContentType = "application/pdf";
MemoryStream ms = new MemoryStream(bytes);
Response.AddHeader("content-disposition", "attachment;filename=" + "fiche abonnement_" + _gNewFile + ".pdf");
Response.Buffer = true;
ms.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
}
if anyone cant give me a tip ! thank you.
If you don't need the file on the file system, you can create it in memory. This is done using a MemoryStream. I took your code, copy/pasted it and adapted it so that the FileStream is replaced by a MemoryStream.
I couldn't test your code, so you may need to tweak it here and there, but you'll get the idea of what you should try to achieve:
var pdfTemplate = HttpContext.Current.Server.MapPath("...");
var pdfReader = new PdfReader(System.IO.File.ReadAllBytes(pdfTemplate));
var output = new MemoryStream();
var pdfStamper = new PdfStamper(pdfReader, output);
var pdfFormFields = pdfStamper.AcroFields;
foreach (var entry in dic)
{
pdfFormFields.SetField(entry.Key, entry.Value);
}
pdfStamper.FormFlattening = true;
pdfStamper.JavaScript = "this.print(true);\r";
pdfStamper.Writer.CloseStream = false;
pdfStamper.Close();
pdfReader.Close();
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment;filename=fiche abonnement_" + _gNewFile + ".pdf");
Response.BinaryWrite(output.ToArray());
Response.Flush();
Response.End();
Can someone give me an example on how to use Apache PDFBox to convert a PDF file in different images (one for each page of the PDF)?
Solution for 1.8.* versions:
PDDocument document = PDDocument.loadNonSeq(new File(pdfFilename), null);
List<PDPage> pdPages = document.getDocumentCatalog().getAllPages();
int page = 0;
for (PDPage pdPage : pdPages)
{
++page;
BufferedImage bim = pdPage.convertToImage(BufferedImage.TYPE_INT_RGB, 300);
ImageIOUtil.writeImage(bim, pdfFilename + "-" + page + ".png", 300);
}
document.close();
Don't forget to read the 1.8 dependencies page before doing your build.
Solution for the 2.0 version:
PDDocument document = PDDocument.load(new File(pdfFilename));
PDFRenderer pdfRenderer = new PDFRenderer(document);
for (int page = 0; page < document.getNumberOfPages(); ++page)
{
BufferedImage bim = pdfRenderer.renderImageWithDPI(page, 300, ImageType.RGB);
// suffix in filename will be used as the file format
ImageIOUtil.writeImage(bim, pdfFilename + "-" + (page+1) + ".png", 300);
}
document.close();
The ImageIOUtil class is in a separate download / artifact (pdf-tools). Read the 2.0 dependencies page before doing your build, you'll need extra jar files for PDFs with jbig2 images, for saving to tiff images, and reading of encrypted files.
Make sure to use the latest version of whatever JDK version you are using, i.e. if you are using jdk8, then don't use version 1.8.0_5, use 1.8.0_191 or whatever is the latest at the time you're reading. Early versions were very slow.
I tried it today with PdfBox 2.0.15.
import org.apache.pdfbox.pdmodel.*;
import org.apache.pdfbox.rendering.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
public static void PDFtoJPG (String in, String out) throws Exception
{
PDDocument pd = PDDocument.load (new File (in));
PDFRenderer pr = new PDFRenderer (pd);
BufferedImage bi = pr.renderImageWithDPI (0, 300);
ImageIO.write (bi, "JPEG", new File (out));
}
public class PDFtoJPGConverter {
public List<File> convertPdfToImage(File file, String destination) throws Exception {
File destinationFile = new File(destination);
if (!destinationFile.exists()) {
destinationFile.mkdir();
System.out.println("DESTINATION FOLDER CREATED -> " + destinationFile.getAbsolutePath());
}else if(destinationFile.exists()){
System.out.println("DESTINATION FOLDER ALLREADY CREATED!!!");
}else{
System.out.println("DESTINATION FOLDER NOT CREATED!!!");
}
if (file.exists()) {
PDDocument doc = PDDocument.load(file);
PDFRenderer renderer = new PDFRenderer(doc);
List<File> fileList = new ArrayList<File>();
String fileName = file.getName().replace(".pdf", "");
System.out.println("CONVERTER START.....");
for (int i = 0; i < doc.getNumberOfPages(); i++) {
// default image files path: original file path
// if necessary, file.getParent() + "/" => another path
File fileTemp = new File(destination + fileName + "_" + i + ".jpg"); // jpg or png
BufferedImage image = renderer.renderImageWithDPI(i, 200);
// 200 is sample dots per inch.
// if necessary, change 200 into another integer.
ImageIO.write(image, "JPEG", fileTemp); // JPEG or PNG
fileList.add(fileTemp);
}
doc.close();
System.out.println("CONVERTER STOPTED.....");
System.out.println("IMAGE SAVED AT -> " + destinationFile.getAbsolutePath());
return fileList;
} else {
System.err.println(file.getName() + " FILE DOES NOT EXIST");
}
return null;
}
public static void main(String[] args) {
try {
PDFtoJPGConverter converter = new PDFtoJPGConverter();
Scanner sc = new Scanner(System.in);
System.out.print("Enter your destination folder where save image \n");
// Destination = D:/PPL/;
String destination = sc.nextLine();
System.out.print("Enter your selected pdf files name with source folder \n");
String sourcePathWithFileName = sc.nextLine();
// Source Path = D:/PDF/ant.pdf,D:/PDF/abc.pdf,D:/PDF/xyz.pdf
if (sourcePathWithFileName != null || sourcePathWithFileName != "") {
String[] files = sourcePathWithFileName.split(",");
for (String file : files) {
File pdf = new File(file);
System.out.print("FILE:>> "+ pdf);
converter.convertPdfToImage(pdf, destination);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
====================================
Here i am use Apache pdfbox-2.0.8 , commons-logging-1.2 and fontbox-2.0.8 Library
HAPPY CODING :)
w/o any extra dependencies you can just use the PDFToImage class already included in PDFBox.
Kotlin:
PDFToImage.main(arrayOf<String>("-outputPrefix", "newImgFilenamePrefix", existingPdfFilename))
other config opts: https://pdfbox.apache.org/docs/2.0.8/javadocs/org/apache/pdfbox/tools/PDFToImage.html
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.nio.file.Path;
public class Pdf2Image {
public String convertPdf2Img(String fileInput, Path path) {
String destDir = "";
try {
String destinationDir = path.toString();
File sourceFile = new File(fileInput);
File destinationFile = new File(destinationDir);
if (!destinationFile.exists()) {
destinationFile.mkdir();
System.out.println("Folder Created -> " + destinationFile.getAbsolutePath());
}
if (sourceFile.exists()) {
PDDocument document = PDDocument.load(sourceFile);
PDFRenderer pdfRenderer = new PDFRenderer(document);
String fileName = sourceFile.getName().replace(".pdf", "");
// int pageNumber = 0;
// for (PDPage page : document.getPages()) {
for (int pageNumber = 0; pageNumber < document.getNumberOfPages(); ++pageNumber) {
BufferedImage bim = pdfRenderer.renderImage(pageNumber);
destDir = destinationDir + File.separator + fileName + "_" + pageNumber + ".png";
ImageIO.write(bim, "png", new File(destDir));
}
document.close();
System.out.println("Image saved at -> " + destinationFile.getAbsolutePath());
} else {
System.err.println(sourceFile.getName() + " File does not exist");
}
} catch (Exception e) {
e.printStackTrace();
}
return destDir;
}
}
Here is part of my code to convert a pdf, from a multipart file, to jpg thumbnail. I'm saving the image as a base64 string. Pdfbox 2.0.21 version was used.
private static String generatePdfThumbnail(byte[] imageInBytesArray) throws IOException {
PDDocument document = PDDocument.load(imageInBytesArray);
PDFRenderer renderer = new PDFRenderer(document);
BufferedImage bufferedImage = renderer.renderImage(0);
Graphics2D bufImageGraphics = bufferedImage.createGraphics();
bufImageGraphics.drawImage(bufferedImage, 0, 0, null);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
boolean foundWriter = ImageIO.write(bufferedImage, "jpg", baos);
byte[] fileContent = null;
if (!foundWriter) {
return "";
}
fileContent = baos.toByteArray();
return Base64.getEncoder().encodeToString(fileContent);
}