It is more convenient to use components to upload images in JSP, but as a beginner, I still want to train my hands first and start from a trivial matter.
You can upload images in either of the following ways: Save the image to a directory on the server and save it to the Database BLOB field.
On the code.
Upload page source code:
[Html]
<HTML>
<HEAD>
<TITLE> upload </TITLE>
<HEAD>
<BODY>
<Form method = post action = "mytest/page/accept. jsp">
Figure: <input type = "file" NAME = "image"> <BR>
<Input type = "submit" value = "submit">
</FORM>
</BODY>
</HTML>
Process upload page:
[Html]
<% @ Page import = "java. io. *" %>
<HTML>
<HEAD>
<TITLE> ac </TITLE>
</HEAD>
<BODY>
<%
/* Here we get the image path. Pay attention to Chinese garbled characters */
String ima = request. getParameter ("image ");
Ima = new String (ima. getBytes ("ISO-8859-1 "));
/* Get the image name */
String filename = ima. substring (ima. lastIndexOf ("\") + 1, ima. length ());
Out. print (filename + "<br>"); // verify the output of www.2cto.com.
Try {
/* Obtain the absolute path of the project, but this method is not recommended, so it is best to set another path */
String path = request. getRealPath ("/");
Out. print (path + "<br> ");
/* Create an output stream pointing to the specified file. After this step, the corresponding file will be created in the directory ,*/
/* You can check it. */
FileOutputStream ot = new FileOutputStream (path + filename );
/* Open the actual connection to a file to establish the input stream. ima refers to the file path. */
FileInputStream in = new FileInputStream (ima );
Byte B [] = new byte [1024];
/* Read data from the input file and write it to the output file */
While (-1! = In. read (B ))
{
Ot. write (B );
}
/* Close the stream */
In. close ();
Ot. close ();
}
Catch (Exception e)
{
System. out. print (e. toString ());
}
%>
</BODY>
Summary:
1 ---- the general idea is very simple. Set up the output stream to the output file (that is, the storage target), then set up the input stream pointing to the source file, and finally read it from the input stream, and output it to the output stream.
2 --- doubt. There is a post on the Internet that is very popular and has no components to upload. I have read it many times. He used many other things: incluimagedecoder, BufferedImage, and incluimageencoder. I understand that, but I think my code is simple, but there may be bugs. I hope you can appreciate it.
From the wkupaochuan Column