2015-03-25 57 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 
    } 
} 

将文件变成变量后,可以将它们插入到数据库中。

相关问题