2015-03-25 88 views
1

我想上傳一些文件扔我的網站到數據庫。在上傳頁面,我用一些領域是這樣的:我怎樣才能上傳文件扔blob objcet數據庫到數據庫

<form method = "post" action="addResumeSvl"> 
    <input type = "file" name="file1"> 
    <input type = "file" name="file2"> 
</form> 

但在addResumeSvl,我怎麼能區分文件1和文件2,諸如此類request.getParameter()方法,然後把它們放到DATEBASE與blob對象

回答

0

在表單他們必須multipart

<form action="addResumeSvl" method="post" enctype="multipart/form-data"> 
現在

post方法中添加以下代碼片段

InputStream inputStream = null; // input stream of the upload file 

    // obtains the upload file part in this multipart request 
    Part filePart = request.getPart("file1"); 
    if (filePart != null) { 
     // prints out some information for debugging 
     System.out.println(filePart.getName()); 
     System.out.println(filePart.getSize()); 
     System.out.println(filePart.getContentType()); 

     // obtains input stream of the upload file 
     inputStream = filePart.getInputStream(); 
    } 

現在,在數據庫存儲使用下面的代碼片段爲file2文件

1

DriverManager.registerDriver(new com.mysql.jdbc.Driver()); 
     conn = DriverManager.getConnection(dbURL, dbUser, dbPass); 

     // constructs SQL statement 
     String sql = "INSERT INTO tablename(columnname) values (?)"; 
     PreparedStatement statement = conn.prepareStatement(sql);    
     if (inputStream != null) { 
      // fetches input stream of the upload file for the blob column 
      statement.setBlob(1, inputStream); 
     } 

     // sends the statement to the database server 
     int row = statement.executeUpdate(); 
     if (row > 0) { 
      message = "File uploaded and saved into database"; 
     } 

同樣的方式做您提交請求,請確保您添加enctype="multipart/form-data作爲對<form>標籤的屬性之前。

<form action="upload" method="post" enctype="multipart/form-data"> 
 
    <input type = "file" name="file1"> 
 
    <input type = "file" name="file2"> 
 
    <input type="submit" /> 
 
</form>

如果你在servlet的3.0或更新可以使用HttpServletRequest#getPart()收集多形式的數據。

@MultipartConfig 
public class UploadServlet extends HttpServlet { 
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
     Part file1 = request.getPart("file1"); //get your file1 
     Part file2 = request.getPart("file2"); // your file2 
    } 
} 

將文件變成變量後,可以將它們插入到數據庫中。

相關問題