While your approach is technical feasible, it's practically problematic (as you are finding).
1) All that disk IO really hurts performance when you gain nothing from it (i.e. you are not putting the file on disk to save it permanently, just as a temporary storage).
2) Because of the performance issue previously mentioned, you are likely to get two users competing for that single file.
3) Using the file system in a web application has it's own set of problems. You have to fight with permissions issues when you deploy such an application.
You should be able to take the file stream from the upload event and save it directly into the database without going through the file system at all. This will be significantly more efficient. Presuming that you have some identifier for the row that contains the image, you can uniquely identify it.
To retrieve the image, you can create a page or HttpHandler to process an image request. Instead of given a URL like: "/myapp/images/img.jpg", you give one that looks like this: "/myapp/getimage.aspx?imageID=123456". When the page runs, you do these steps:
- Clear the response buffer (so there isn't anything emitted to start)
- Change the Response.ContentType to the appropriate data type (image/jpeg for example)
- Use the BinaryWrite method to stream the image binary data
- End the response.
Here's some code I used that does this:
Code:
_oResponse.Clear()
_oResponse.ContentType = "image/jpeg"
_oResponse.BinaryWrite(objStream.ToArray)
objStream.Close()
_oResponse.Flush()
_oResponse.End()
You'll have to populate objStream with the data from the record in the database.
-
Peter