Upload & rename files ?

rbb

Member
Joined
Jul 19, 2004
Messages
21
I have a question regarding the uploading of files to a ASP.Net & SQL 2k5 based application. After the user uploads their file to the server, I usually save the file name in a table, and rename actual file to match the unique ID of the promotion (1 attachment per promotion). This way I dont have to worry about duplicate filenames. However, when they hover over the link to view the attachment, they will see the path the actual file, which is /folder/123 instead of /folder/yourattachment.pdf. Which in turn makes it difficult for the browser to know which application to open the attachment with.

Is there a workaround for this? Something like renaming the file just in time? Or copying the file to a temporary location and renaming it? Or do most people have a seperate folder for each record (promotion)?



Thanks,

Rob
 
Create a file serving page

This is the approach I would take.

I would create a dummy ASP.Net page which is used solely for serving up files. The file to serve is specified as a querystring parameter. Lets imagine this page is called GetFile.aspx and expects a parameter fn. The code behind GetFile looks for the parameter and then sends the appropriate file to the client.

This in itself wont solve your problem of the client not knowing what kind of file it is being served. This function is carried out by the ContentType of the response. Your code for GetFile might then look something like this:

VB:
Code:
Dim fileName As String = Request.QueryString("fn")

Here, check fileName refers to a valid file

Here, get the LOCAL file path from database
Dim filePath As String = "\folder\" & fileName

Here, we must set the appopriate content/MIME type
Dim mimeType As String = "application/octet-stream" Default

Send the file
Response.Clear()
Response.ContentType = mimeType
Response.AddHeader("Content-Disposition", "attachment; filename=" & fileName)
Response.WriteFile(filePath)
Response.End()

C#:
C#:
string fileName = Request.QueryString("fn");

//Here, check fileName refers to a valid file

//Here, get the LOCAL file path from database
string filePath = "\\folder\\" + fileName;

//Here, we must set the appopriate content/MIME type
string mimeType = "application/octet-stream"; //Default

//Send the file
Response.Clear();
Response.ContentType = mimeType;
Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
Response.WriteFile(filePath);
Response.End();

In your other page you would place a link to GetFile.aspx?fn=yourattachment.pdf or something like that.

Of course this method requires you to look up the MIME type associated with each file extension, or default to application/octet-stream. However, it allows you to give the client an exact filename which may differ from the filename used to store the file locally.

Good luck :cool:
 
Back
Top