구글와이드(336x280)_상단 2개


(영문)Uploading Images using HTML and ASP ASP, ASP.NET

Uploading Images using HTML and ASP
By Jos Vernon (jos@websupergoo.com)
Why should you let visitors upload pictures onto your Web site?
Well lets take a couple of examples. People renting their holiday homes might like to display a picture of the property on a Web site. News sites might like to allow people to send them pictures of events in their area. Ideally we would like the visitor to be able to upload these pictures themselves using their standard Web browser.
Unfortunately images come in thousands of different formats, shapes, colors and sizes; almost none of which will mesh in with your beautifully designed site. This article is about how we can best solve this problem. To do this we will have to search down into the depths of HTML and ASP.
Digging down, the first gem we find is HTML upload. This is based around a standard, but vastly underused, HTML form element. When you put it into a form on a Web page it allows you to choose a file. When you submit the form, the file is sent to the Web server. What could be more perfect?
The second gem we find is the vast range of Active Server Page Extensions that exist on the market. These ActiveX controls add extra functions to the standard Active Server Page repertoire and can be accessed from simple scripting languages such as VBScript. The ASP Extension we will use here is the ImageGoo (http://www.websupergoo.com) Web graphics toolkit as it incorporates everything we need in one package.
In which we discover the hidden wonders of HTML file uploads.
The HTML file upload form element is standard, but vastly underused. It allows you to create forms that can send entire files to your Web server. As a visitor it appears as just another part of just another form. You click on the file upload button to choose a file. When you submit the form the file is posted along with the rest of the form data.
Like so many useful elements of HTML, file upload was not supported in Internet Explorer 3.0 but was soon afterwards added in version 3.02. It is available in Netscape Navigator from version 2.02 onwards.
So what does it look like? Well check out the (non-functional) form below - pretty much like any other form element except that you can use the browse button to choose files.
Enter Some Text:

Choose a File:


What about the code? Well again, pretty much like any other piece of form HTML. Here's the code for the above.
<form method="post" action="photoupload.asp" name="submit" enctype="multipart/form-data">
Enter Some Text: <input type="text" name="textfield"><br><br>
Choose A File: <input type="file" name="filefield"><br><br>
<input type="submit" name="su bmit" value="submit"><br>
</form>
There are only a couple of real differences. The input type of the file upload is 'file' rather than 'text.' The 'enctype' of the form is 'multipart/form-data' - about which more of later.
Multipart Form Data
Uploading Images using HTML and ASP
In which 'multipart/form-data' rears its ugly head.
What is 'multipart/form-data'?
It's an Internet standard for sending lots of different types of information over the Internet as one bundle. However it doesn't really make much difference what it is because we're only interested in getting the file back out and herein lies Dark Secret Number One.
- ASP doesn't support 'multipart/form-data' as standard!
It is a Shocking Revelation that although Microsoft browsers have supported this format from the moment that Microsoft got interested in the Web, the standard form components they supply for Web serving do not. However help is at hand; there are a vast range of ASP Extensions designed specifically to solve this problem. For instance Software Artisans (http://www.softartisans.com) and more recently Microsoft now produce solutions.
When choosing your solution you should bear in mind that file upload is not as simple as it might seem and herein lies Dark
Secret Number Two.
- Some browsers encode files before transmitting them!
A number of browsers on the MacOS upload files encoded as MacBinary (to allow special Mac specific features to be transmitted). While Mac browsers will normally make up only 10% of your visitors, in some picture related industries like publishing you may find that this proportion approaches 100%. If you use a third party component you should ensure that it supports MacBinary.
We will use the solution that comes bundled with ImageGoo as it's no effort and it fulfils all these requirements.
Decoding the Upload/Manipulating the Image
Uploading Images using HTML and ASP

Decoding the Upload

In which our server grabs the image out of the data it's been sent.
From the ASP side we need to get the picture file out of the data we receive. Using ImageGoo the code to do this is pretty straightforward. We have already set the file 'photoupload.asp' as our form action. In this we include the following code.
Set mp = Server.CreateObject("ImageGoo.XMultipart")
data = Request.BinaryRead(Request.TotalBytes)
mp.SetData(data)
Set field1 = mp.Item("filefield")
Set field2 = mp.Item("textfield")
That's all there is to it! We start off by creating the object we're going to be using (the ImageGoo XMultipart object). We then read the raw data that's been sent to us and put it into the object.
To get the fields out we just ask for the Item with the same name as the form field. So we ask for the field called 'filefield' and then for the field called 'textfield'. Each of these is an object that holds everything we need to know about the contents of each field. We'll keep these field objects handy for later on.

Manipulating the Image

In which ImageGoo makes the picture all respectable.
Who knows what the image we have is like? It's probably the wrong size and shape. It's probably the wrong format. The only thing you can guarantee for sure is that it's not going to look good if we just insert it into our web page. So let's get ImageGoo to turn it into something more respectable.
First the size. We have a fixed amount of space for our image. Generally the height doesn't matter too much because a tall image will just push other content down the page, however the width does. If the image is too wide you won't be able to see all of it. If the image is too narrow your page will look plain silly and tables may slip into the space that's been left.
To keep things simple let's make the width fixed. If the image is too big we'll scale it down. If it's too small we won't scale it up (because it would result in horrible pixellation) but we'll center it. To do this we use the following code.
Set canvas = Server.CreateObject("ImageGoo.Canvas")
canvas.Width = 290
rect = canvas.DrawData(field1.Data, field1.Filename, "Fit=True VAlign=middle HAlign=middle")
First we create a canvas to draw on and set a width of 290 pixels. Next we draw the image onto the canvas. We pass DrawData both the raw data from the field object we obtained earlier and the filename. The filename is not strictly necessary but is useful as a hint to the type of image. Because the width has been fixed the height will be set automatically to fit with the shape (aspect ratio) of the image we are drawing.
The Fit parameter specifies that the image should be fitted into the canvas. This means it will be scaled down if it is too large but the shape (aspect ratio) will never be altered. When the image is drawn it is normally drawn at the top left of the canvas but by setting the HAlign and VAlign parameters we can ensure that it is drawn in the centre (useful if the image is small).
So now we have a canvas with our image on it. Let's put a frame round the edge.
canvas.DrawShape "rect", "Operation=draw"
Because the size has not been specified ImageGoo assumes that the rectangle should be the same size as the canvas. We use the draw operation to override the outline and fill that would normally be performed on the rectangle.
And now some rotated text up the right-hand side.
canvas.TextFont = "Arial"
canvas.TextSize = 7
canvas.TextColor = "gray"
canvas.Width = canvas.Width + 20
canvas.DrawText field2.Contents, "Rotate=-90 Translate=290," & (canvas.Height - 2)
First we set the style of text we're going to draw (Arial 7point Gray). Next we have to increase the width of the canvas to make room for the text. Finally we draw the text from the text field object we picked up earlier. By default the text is drawn at the top left of the canvas so we rotate the text 90 degrees anticlockwise and move (translate) it down to the bottom right.
So what might it look like? Here's one I prepared earlier.
Original from the National Oceanic and Atmospheric Administration/Department of Commerce by Dr. James P. McVey, 1968.
Saving the File/Browser Caching for Masochists

Uploading Images using HTML and ASP

Saving the File

In which we insert the image into our Web site.
So now we have a canvas with an image on it. How do we get it into our Web site? You could upload it to a database and serve it when requested but here we're going to just save it out into an appropriate directory on our server.
Once again the code is very simple.
path = Server.MapPath("../images/final.jpg")
canvas.SaveAs path, "Quality=normal"
First we find the physical path to the hyperlink required using the standard MapPath call. Then we ask the canvas to save a copy of itself to this path. It will be saved as a JPEG because the file path specifies the file name as 'final.jpg'.
So why didn't we save it as 'final.gif'?
Unisys holds the patent on LZW compression which is used to produce GIF images. They have a policy that requires large fees to be paid for each Web server that uses this technology. To get around this problem, all Web toolkits produce uncompressed GIF images. The expansion in size depends on the type of image but may typically be a factor of between 2 and 3 for photo style images.
So although we could have saved it out as a GIF, JPEG is a better option unless you wish to use transparency.
There are techniques that allow you to produce 'real' LZW GIF images but these are complicated and require a fair investment of time.

Browser Caching for Masochists

In which we discuss the pain of browser image caching
Often it is quite enough to just save an image out to a directory and then reference it from other pages in your web site. However it is worth noting that browsers cache images in a different way from HTML. If you are going to be overwriting an image frequently you should consider the following.
If you replace an image which a browser has already cached it will not always reload it. Different browsers work in different ways but assuming the href to the image is the same some will pick up and reload the image immediately, some will reload it if you click on refresh, and some will only reload it if you do a forced refresh (command refresh). Most will pick up on the new image if you quit the browser and restart it but again this is dependent on browser settings. Herein lies our final Dark Secret Number 3.
- The only way to ensure that an image will be reloaded is to change the href
You can ensure that all your images are reloaded appropriately using a nifty piece of ASP. There are other more efficient ways of accomplishing this for different tasks but this does the job nicely for us.
We assign a directory for our image rather than a filename for our image. Each time we replace the image we change the filename. Each time a page of HTML references the image we use a piece of ASP code to look in the directory and insert the current filename. So what does the code for this look like?
To insert a file into the directory we use the following piece of code.
DeleteFilesFromURL("../images/final/")
Randomize()
path = Server.MapPath("../images/final/" & Int(1000000 * Rnd) & ".jpg")
canvas.SaveAs path, "Quality=normal"
Public Sub DeleteFilesFromURL (inFolderURL)
Set fso = Server.CreateObject("Scripting.FileSystemObject")
Set fold = fso.GetFolder(Server.MapPath(inFolderURL))
For Each file in fold.Files
ext = LCase(Right(file.Name, 4))
If ext = ".jpg" Then file.Delete
Next
End Sub
We start by deleting all the files from the directory. There should only be a maximum of one of these but you can't be too sure. After this we generate a random name for the file and save the image out with this name.
The DeleteFilesFromURL function is quite straightforward. It looks in the folder specified and iterates through all the files deleting any JPEGs. We limit it to JPEGs in case you accidentally drop your life's work - The Great American Novel - into the directory by mistake.
To insert the appropriate href into your page of HTML we use the following code.
GetFileFromURL("../images/final/")
Public Function GetFileFromURL (inFolderURL)
Set fso = Server.CreateObject("Scripting.FileSystemObject")
Set fold = fso.GetFolder(Server.MapPath(inFolderURL))
name = ""
For Each file in fold.Files
name = file.Name
Exit For
Next
GetFileFromURL = inFolderURL & name
End Function
All this does is to look in the directory specified and return the first file found. Couldn't be simpler, now all you've got to do is incorporate it into your site.

null



바보들의 영문법 카페(클릭!!)

오늘의 메모....

시사평론-정론직필 다음 카페
http://cafe.daum.net/sisa-1

바보들의 영문법 다음 카페
http://cafe.daum.net/babo-edu/

티스토리 내 블로그
http://earthly.tistory.com/

내 블로그에 있는 모든 글들과 자료에 대한 펌과 링크는 무제한 허용됩니다.
(단, 내 블로그에 덧글쓰기가 차단된 자들에게는 펌, 트랙백, 핑백 등이 일체 허용되지 않음.)

그리고 내 블로그 최근글 목록을 제목별로 보시려면....
바로 아래에 있는 이전글 목록의 최근달을 클릭하시면 됩니다.
그러면 제목을 보고 편하게 글을 골라 보실 수 있습니다.

그리고 내 블로그내 글을 검색하시려면 아래 검색버튼을 이용하시면 됩니다.


가가챗창

flag_Visitors

free counters