Hi, I am also a beginner but I have just gotten this working on my machine using MYSQL. The Database part was easy but getting the other stuff working was a bit difficult for me. I used the following instructions:
1)Upload File Part
Note that this is a three page tutorial with the source files on the 1st page. So after you read page three, go to page one to get the files downloaded.
This all worked perfectly after adding the appropriate .jar files and classpath stuff.
2)Database part. On the page called fileuploaddemo.jsp there is a section of the code that deals with uploading a file:
// the item must be an uploaded file
// save it to disk
File fullFile = new File(item.getName());
File savedFile = new File(getServletContext().getRealPath("/"), fullFile.getName());
item.write(savedFile);
//I added these lines to write to my database. They use the class which I wrote and is stored in a java class file.
UploadDB myDBFunctions = new UploadDB();
int up = myDBFunctions.insertFile(fullFile);
//BELOW IS THE JAVA CLASS. You mentioned you wanted to do it all in JSP. It would probably look similar anyway though.
package package_name;
import java.io.File;
import java.io.FileInputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
/**
*
* @author BUCKET
*/
public class UploadDB {
/** Creates a new instance of UploadDB */
public UploadDB() {
}
public int insertFile(File f) throws Exception{
// connection instance
Connection connection = null;
FileInputStream fis = null;
int myint = 0;
File file = new File("/Users/you_computer_name/file_path/test.mp3");
fis = new FileInputStream(file);
//My test table in the db has one field - file_name it is a BLOB
String sqlInsertFile = "INSERT INTO files (file_name) VALUES ('" + file + "')";
try {
// connect to database
DataSource dataSource = getJdbcConnectionPool();
connection = dataSource.getConnection();
PreparedStatement ps = connection.prepareStatement(sqlInsertFile);
myint = ps.executeUpdate();
} catch(Exception e){
System.out.println(e.getMessage());
} finally{
// close the connection so it can be returned to
// the connection pool then return the list
connection.close();
return myint;
}
}
//Here I used a connection Pool. However there is plenty of examples on google of how to connect directly.
private DataSource getJdbcConnectionPool() throws NamingException {
Context c = new InitialContext();
return (DataSource) c.lookup("java:comp/env/jdbc/connectionPoolWiz");
}
}
I hope this helped a bit. Like I said, I am new to this as well and it took me a few days of having no idea what to do before I got it working. If you have some success let me know. I am currently stuck on how to get the file back out of the database! Good luck.