0

i want to upload files(all format) to a server and store the file location in a database(MySQL)i tried storing the files(all format)in a database using long-blob format,but it is not accepting the file size of not more-then 1kb and it accepts only text file. here is my html code

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>
</head>
<body>
    <form enctype="multipart/form-data" action="upload.jsp" method="post">
        <br/><br/><br/>
        <center>
            <table border="0" bgcolor=#ccFDDEE>
                <tr>
                    <td colspan="2" align="center"><b>UPLOAD THE FILE</b></td>
                </tr>
                <tr>
                    <td colspan="2" align="center"> </td>
                </tr>
                <tr>
                    <td><b>Choose the file To Upload:</b></td>
                    <td><INPUT NAME="file" TYPE="file">      </td>
                </tr>
                <tr>
                    <td colspan="2" align="center"> </td>
                </tr>
                <tr>
                    <td colspan="2" align="center"><input type="submit" value="Send File"> </td>
                </tr>
            <table>
        </center> 
    </form>
</body>
</html>

here is my jsp code for storing files to a database(using long-blob).

<%@ page import="java.io.*,java.sql.*" %>
<%
String saveFile="";
String contentType = request.getContentType();
if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) {
    DataInputStream in = new DataInputStream(request.getInputStream());
    int formDataLength = request.getContentLength();
    byte dataBytes[] = new byte[formDataLength];
    int byteRead = 0;
    int totalBytesRead = 0;
    while (totalBytesRead < formDataLength) {
        byteRead = in.read(dataBytes, totalBytesRead,formDataLength);
        totalBytesRead += byteRead; 
    }
    String file = new String(dataBytes);
    saveFile = file.substring(file.indexOf("filename=\"") + 10);
    saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
    saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1,saveFile.indexOf("\""));
    int lastIndex = contentType.lastIndexOf("=");
    String boundary = contentType.substring(lastIndex + 1,contentType.length());
    int pos;
    pos = file.indexOf("filename=\"");
    pos = file.indexOf("\n", pos) + 1;
    pos = file.indexOf("\n", pos) + 1;
    pos = file.indexOf("\n", pos) + 1;
    int boundaryLocation = file.indexOf(boundary, pos) - 4;
    int startPos = ((file.substring(0, pos)).getBytes()).length;
    int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;
    saveFile="/home/adapco/Desktop"+saveFile;
    File ff = new File(saveFile);
    FileOutputStream fileOut = new FileOutputStream(ff);
    fileOut.write(dataBytes, startPos, (endPos - startPos));
    fileOut.flush();
    fileOut.close();
%>
<br>
    <table border="2">
        <tr>
            <td><b>You have successfully upload the file by the name of:</b><% out.println(saveFile);%></td>
        </tr>
    </table>
<%
    Connection connection = null;
    String connectionURL = "jdbc:mysql://localhost:3306/ksa";
    ResultSet rs = null;
    PreparedStatement psmnt = null;
    FileInputStream fis;
    try {
        Class.forName("com.mysql.jdbc.Driver").newInstance();
        connection = DriverManager.getConnection(connectionURL, "root", "root");
        File f = new File(saveFile);
        psmnt = connection.prepareStatement("insert into file(file_data) values(?)");
        fis = new FileInputStream(f);
        psmnt.setBinaryStream(1, (InputStream)fis, (int)(f.length()));
        int s = psmnt.executeUpdate();
        if(s>0) {
            System.out.println("Uploaded successfully !");
        }
        else{
            System.out.println("unsucessfull to upload file.");
        }
    }
    catch(Exception e){
        e.printStackTrace();
    }
}
%>

now i have to store the files either to a server and storing its path to db or to store the files(all formats)in a database using long-blob type.iam using netbeans and glassfish server(red hat linux).give me some idea.

david
  • 3,225
  • 9
  • 30
  • 43
ksa
  • 311
  • 1
  • 10
  • 29
  • wouldn't it be great, if you store the files at some designated location on server and save only the path in database. That way rendering will be fast, DB will be less complex – Satya Apr 20 '12 at 07:01
  • but i cant store all file formats with my above code and also it is not accepting not more than 1kb.any solution? – ksa Apr 20 '12 at 07:05
  • change the code, move to any ajax based file uploader , and you can upload virtually anything :) – Satya Apr 20 '12 at 07:06
  • what's wrong with my code,can u point out? – ksa Apr 20 '12 at 07:07
  • I have checked your code and seems working with other file format and more than 1 KB with Tomcat.But It is good practice to store files at hard disk location and store its path in database. – Hardik Mishra Apr 20 '12 at 07:47
  • @hardik is there any thing wrong with glassfish. – ksa Apr 20 '12 at 07:51
  • Can't say. I have not worked with Glassfish. BTW this works only if you have only file in HTML form. If you want to upload file with other form parameters Check http://stackoverflow.com/questions/2422468/how-to-upload-files-in-jsp-servlet. BaluSC 's answer – Hardik Mishra Apr 20 '12 at 07:54
  • 1
    Your code? This is clearly a ripoff from roseindia.net. Please put that site in your internet blacklist. For an overview of what's all wrong with it please see http://stackoverflow.com/questions/5038798/uploading-of-pdf-file/5041420#5041420 Do not ever visit roseindia.net, it would only lead to trouble in all colors and your conceptual understanding of basic web development in general would be totally wrong for years. – BalusC Apr 20 '12 at 13:45
  • @balus:ur wright,any way i have used oreilly api for file transfer. now it is working fine. – ksa Apr 23 '12 at 05:18
  • @ksa: the Oreily API is very ancient and has some specific bugs. Rather use Apache Commons FileUpload as mentioned in the below answer and in the link which I posted in my previous comment. – BalusC Apr 23 '12 at 11:30
  • @Satya:can u post ur last 2 comments,previous conversation is deleted to this link http://stackoverflow.com/questions/10494013/retrieving-files-from-database-by-their-path-in-jsp/10494030#comment13565213_10494030 sorry for using older post – ksa May 08 '12 at 09:07

2 Answers2

0

I strongly advice you use one of the existing modules people have built for multipart file upload handling. Commons Fileupload is on of the more popular, I suggest you look into it (usage example here).

Your code is pretty messy and you are mixing working with byte arrays and Strings in a way that is sure to create errors. This:

int boundaryLocation = file.indexOf(boundary, pos) - 4;
int startPos = ((file.substring(0, pos)).getBytes()).length;
int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;
...
fileOut.write(dataBytes, startPos, (endPos - startPos));

is particularly hairy. Anyway, if you insist on doing it yourself, you should clean up your code, don't mix working with Strings and byte arrays (remember, one character in a string is not necessarily just one byte). I don't recommend it though, unless this is a learning experience for you. In which case I would spend some time to try and find some example code on the internet for multipart form handling.

pap
  • 27,064
  • 6
  • 41
  • 46
0

Use mediumblob(upto 16mb upload) or longblob(upto 1 gb or 4 gb) in mysql. and add below the [mysqld] line in my.ini

  • if you use mediumblob in mysql: max_allowed_packet=16M
  • if you use largeblob in mysql: max_allowed_packet=1024M
towi
  • 21,587
  • 28
  • 106
  • 187