How to upload and download a file - asp.net

I like to upload an file in my project. when I click the upload button the file should be stored in client system and the file name and path should be stored in the database. When I clicking the download button it should be downloaded based on the file name and path that I have stored in the database. After making the changes it should be uploaded as different file name and it will not affect the previous file content. If there is any code for this process please send it to me.
Thanks in advance

To upload a file you use the input type file and then process this accordingly on the server. Here is a complete tutorial on CodePlex that goes through exactly what you are looking for.
Warning don't use their code in production. Just noticed a couple of security risks, but anyways, use this to understand the process then figure out how to avoid sql-injections and possible overflows.
Here is another great article over at MSDN that covers File Uploading in ASP.NET 2.0.

string FolderPath = "yourpath";
string FileName = "Namefile";
string FilePath = Server.MapPath("~/" + FileName);
string Extension = Path.GetExtension(FileName);
Response.ContentType = "Application/x-msexcel";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + FileName + "");
// Write the file to the Response
const int bufferLength = 10000;
byte[] buffer = new Byte[bufferLength];
int length = 0;
Stream download = null;
try {
download = new FileStream(Server.MapPath("~/" + FileName),
FileMode.Open,
FileAccess.Read);
do {
if (Response.IsClientConnected) {
length = download.Read(buffer, 0, bufferLength);
Response.OutputStream.Write(buffer, 0, length);
buffer = new Byte[bufferLength];
}
else {
length = -1;
}
}
while (length > 0);
Response.Flush();
Response.End();
}
finally {
if (download != null)
download.Close();
}

Related

Microsoft Word Docx Download Attachment Error

I have doc or docx document saved in Unix directory and integrate with web page which allow user to download the attachment. I have following code to stream the character and saves as Word document with correct MIME type but why when open it shows garbage character. It is relate to character encoding problem. How to solve this? Should I use docx4j?
String fullfilename = filename;
File f = new File(fullfilename);
int length = 0;
ServletOutputStream op = response.getOutputStream();
ServletContext context = getContext();
String mimetype = context.getMimeType(fullfilename);
response.setContentType((mimetype != null) ? mimetype
: "application/x-download");
response.setContentLength((int) f.length());
response.setHeader("Content-Disposition", "attachment;filename="
+ filename);
byte[] bbuf = new byte[fullfilename.length()];
DataInputStream in = new DataInputStream(new FileInputStream(f));
while ((in != null) && ((length = in.read(bbuf)) != -1)) {
op.write(bbuf, 0, length);
}
in.close();
op.flush();
op.close();
Please help. Thanks.
Thread closed after setting the correct mime type.

Download File Servlet - File Content contains binary

I had tried to develop a servlet that allow user to download file but it allow user to download the file but the file content contains binary garbage and not human readable. May I know what could be the reason ?
Code
int length = -1, index = 0;
byte[] buffer = null;
String attachmentPath = null, contentType = null, extension = null;
File attachmentFile = null;
BufferedInputStream input = null;
ServletOutputStream output = null;
ServletContext context = null;
attachmentPath = request.getParameter("attachmentPath");
if (attachmentPath != null && !attachmentPath.isEmpty()) {
attachmentFile = new File(attachmentPath);
if (attachmentFile.exists()) {
response.reset();
context = super.getContext();
contentType = context.getMimeType(attachmentFile.getName());
response.setContentType(contentType);
response.addHeader("content-length", String.valueOf(attachmentFile.length()));
response.addHeader("content-disposition", "attachment;filename=" + attachmentFile.getName());
try {
buffer = new byte[AttachmentTask.DEFAULT_BUFFER_SIZE];
input = new BufferedInputStream(new FileInputStream(attachmentFile));
output = response.getOutputStream();
while ((length = input.read(buffer)) != -1) {
output.write(buffer, 0, length);
index += length;
// output.write(length);
}
output.flush();
input.close();
output.close();
} catch (FileNotFoundException exp) {
logger.error(exp.getMessage());
} catch (IOException exp) {
logger.error(exp.getMessage());
}
} else {
try {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
} catch (IOException exp) {
logger.error(exp.getMessage());
}
}
It is relate to writing file as binary or text mode or browser settings?
Please help.
Thanks.
The problem is not in the code given so far. You're properly using InputStream/OutputStream instead of a Reader/Writer to stream the file.
The cause of the problem is more likely in the way how you created/saved the file. This problem will manifest when you've used a Reader and/or Writer which is not been instructed to use the proper character encoding for the characters being read/written. Perhaps you're creating an upload/download service and the fault was in the upload process itself?
Assuming that the data is in UTF-8, you should have created the reader as follows:
Reader reader = new InputStreamReader(new FileInputStream(file), "UTF-8"));
and the writer as follows:
Writer writer = new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
But if you actually don't need to manipulate the stream on a per-character basis, but just wanted to transfer the data unmodified, then you should actually have used InputStream/OutputStream all the time.
See also:
Unicode - How to get the characters right?

File not found exception once deployed to Server

I am using the below code to Upload an Image file to a SharePoint Document Library. The code works fine locally but once deployed to server, i get the Exception as file not found.
String fileToUpload = FlUpldImage.PostedFile.FileName; //#"C:\Users\admin.RSS\Desktop\Photos\me_skype.jpg";
String documentLibraryName = "SiteAssets";
if (!System.IO.File.Exists(fileToUpload))
throw new FileNotFoundException("File not found.", fileToUpload);
SPFolder myLibrary = web.Folders[documentLibraryName];
// Prepare to upload
Boolean replaceExistingFiles = true;
String fileName = CheckStringNull(txtFirstName.Text) + CheckStringNull(txtLastName.Text) + CheckDateNull(txtDOB) + System.IO.Path.GetFileName(fileToUpload); ;
if (fileName.Contains('/'))
{
fileName = fileName.Replace("/", "");
}
if (fileName.Contains(':'))
{
fileName = fileName.Replace(":", "");
}
FileStream fileStream = File.OpenRead(fileToUpload);
//Upload document
SPFile spfile = myLibrary.Files.Add(fileName, fileStream, replaceExistingFiles);
string url = site.ToString() + "/" + spfile.ToString();
if (url.Contains("="))
{
url = url.Split('=')[1];
}
//Commit
myLibrary.Update();
The string fileupload contains URL as C:\Users\admin.RSS\Desktop\Photos\me.jpg This URL is actually the client system and the server side code throws exception as file not found. How to handle this issue?
UPDATE:
I removed the lines of code that checks if the file exists and now i get the exeption on FileStream fileStream = File.OpenRead(fileToUpload); as c:\windows\system32\inetsrv\20120605_133145.jpg cold not be found
Kindly help. Thank You
if (this.fuAvatarUpload.HasFile && this.fuAvatarUpload.PostedFile.FileName.Length > 0)
{
string extension = Path.GetExtension(file.FileName).ToLower();
string mimetype;
switch (extension)
{
case ".png":
case ".jpg":
case ".gif":
mimetype = file.ContentType;
break;
default:
_model.ShowMessage("We only accept .png, .jpg, and .gif!");
return;
}
if (file.ContentLength / 1000 < 1000)
{
Image image = Image.FromStream(file.InputStream);
Bitmap resized = new Bitmap(image, 150, 150);
byte[] byteArr = new byte[file.InputStream.Length];
using (MemoryStream stream = new MemoryStream())
{
resized.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
byteArr = stream.ToArray();
}
file.InputStream.Read(byteArr, 0, byteArr.Length);
profile.ImageUrl = byteArr;
profile.UseGravatar = false;
profileService.UpdateProfile(profile);
this._model.ShowApprovePanel();
}
else
{
_model.ShowMessage("The file you uploaded is larger than the 1mb limit. Please reduce the size of your file and try again.");
}
}
Saving the file physically onto server and than working on the same helped me resolve my issue.

download report as pdf using servlet

I have the pdf file location and pdf file in my POJO class. I want to download thee pdf using servlet. Please tell me some ways to get it done.
File Location=/tmp/SWBC_444Thu May 03 20:01:07 IST 20124366242221752147545.pdf
Using this file location i want to prompt user to download the file as pdf.
Here is my code.
File file = new File(filePath);
OutputStream responseOutputStream = response.getOutputStream();
response.setContentLength((int)filePath.length());
FileInputStream fileInputStream = new FileInputStream(file);
int size = fileInputStream.available();
byte[] content = new byte[size];
int bytesRead;
while ((bytesRead = fileInputStream.read(content)) != -1)
{
responseOutputStream.write(content, 0, bytesRead);
}
responseOutputStream.flush();
fileInputStream.close();
responseOutputStream.close();
. I read and generate the file but when open the file its empty.
Thanking you..!
httpservletresponse.setHeader("Content-disposition", "attachment; filename=\"" + title + ".pdf\""); should do

How do I set Filestream from an fileupload control?

This is my code and I can't seem to get the file I have in my FileUploadCotrol into the FILESTREAM.
// The buffer size is set to 2kb
int buffLength = 2048;
byte[] buff = new byte[buffLength];
int contentLen;
// Opens a file stream (System.IO.FileStream) to read the file to be uploaded
FileStream fs = fileInf.OpenRead();
try
{
// Stream to which the file to be upload is written
Stream strm = reqFTP.GetRequestStream();
// Read from the file stream 2kb at a time
contentLen = fs.Read(buff, 0, buffLength);
// Till Stream content ends
while (contentLen != 0)
{
// Write Content from the file stream to the FTP Upload Stream
strm.Write(buff, 0, contentLen);
contentLen = fs.Read(buff, 0, buffLength);
}
// Close the file stream and the Request Stream
strm.Close();
fs.Close();
}
It seems the I should be using the Fileupload control to do the from my website, yet it seams strange that the control creates a stream and not a filestream. Yes I am FTPing a file.
Here is a sample method that takes the two types we are targeting, FileInfo and FtpWebRequest, as arguments and streams data between them. I believe this will work.
void UploadFileToFtp(FileInfo file, FtpWebRequest req)
{
int buffLength = 2048;
using (var reader = new BinaryReader(file.OpenRead()))
{
using (var writer = new BinaryWriter(req.GetRequestStream()))
{
while (reader.PeekChar() > 0) writer.Write(reader.ReadBytes(buffLength));
}
}
}
Hope this helps!

Resources