jfinal form表单提交文件

前台代码

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ include file="/commons/taglib.jsp" %>
<%@ include file="/commons/common.jsp" %>
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'excelImp.jsp' starting page</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
    <script type="text/javascript" src="${basePath}/js/sg/jquery-1.9.1.js"></script>
  </head>
  <body>
    <form id="file_form" action="${basePath }/excel/upload" enctype="multipart/form-data"
        method="post"  οnsubmit="return validate()">
        <input type="file" name="file" id="file_input" /> 
        <input type="submit" value="文件上传" id='upFile-btn'>
    </form>
  </body>
  <script type="text/javascript">
     
     function validate(){
         var fileName = $("#file_input").val();
         if (fileName === "") {
             alert("请选择文件");
             return false;
         }
         var fileType = (fileName.substring(fileName
                 .lastIndexOf(".") + 1, fileName.length))
                 .toLowerCase();
         if (fileType !== "xls" && fileType !== "xlsx") {
             alert("文件格式不正确,请选择excel文件!");
             return false;
         }

         $("#file_form").ajaxSubmit({
             dataType : "json",
             success : function(data, textStatus) {
                 if (data.result === "OK") {
                     alert("上传文件成功");
                 } else {
                     alert("文件格式错误");
                 }
                 return false;
             }
         });
         return true;
     }
    </script>

</html>

后台文件接收:

public void upload(){  
        try {
//            HttpServletRequest request = getRequest();  
//            String basePath = request.getContextPath();   
            String ftype = getPara("ftype");
            System.out.println("数据类型:"+ftype);
            //存储路径  
            String path = getSession().getServletContext().getRealPath(Preference._PATH);  
            UploadFile file = getFile("file");  
            String fileName = "";  
            if(file.getFile().length() > 200*1024*1024) {  
                System.out.println("文件长度超过限制,必须小于200M");  
                setAttr("result", "文件长度超过限制,必须小于200M");  
            }else{
                //上传文件
//                String type = file.getFileName().substring(file.getFileName().lastIndexOf(".")); // 获取文件的后缀  
//                fileName = System.currentTimeMillis() + type; // 对文件重命名取得的文件名+后缀  
//                String dest = path + "/" + fileName;  //新的文件路径+文件名
//                System.out.println("新的文件路径+文件名:"+dest);  
//                file.getFile().renameTo(new File(dest));  
//                //读取文件内容
//                File filen = new File(dest);
                List<String[]> list = POIUtil.readExcel(file.getFile());
                for (int i = 0; i < list.size(); i++) {
                    String[] str = list.get(i);
                    
                    Db.use("db1").update("insert into ics_tasks (query, taskid, tname, ttype, btype) "
                            + "values ('"+str[0]+"','"+JavaUtil.getCRC32(str[0])+System.currentTimeMillis()+"','"+str[1]+"','"+str[2]+"','"+str[3]+"')");
                    
                }
                
//                String realFile = basePath + "/" + Preference._PATH +  fileName;          
//                String fname="/"+fileName;
//                setAttr("fname", fname);  
//                setAttr("url", realFile);  
                
                setAttr("result", "OK");  
            }
        } catch (Exception e) {
            e.printStackTrace();
            setAttr("result", e.getMessage());  
        }  
              
        renderJson();  
    }  

参考:http://blog.csdn.net/the_first_c/article/details/72868119

转载于:https://www.cnblogs.com/learningJAVA/p/7495819.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我可以为您提供一个参考代码,您可以根据您的具体需求进行修改: ```java import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/deleteMessage") public class DeleteMessageServlet extends HttpServlet { private static final long serialVersionUID = 1L; private static final String DB_URL = "jdbc:mysql://localhost:3306/mydb"; private static final String DB_USER = "root"; private static final String DB_PASSWORD = "root"; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String title = request.getParameter("title"); Connection conn = null; PreparedStatement stmt = null; try { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD); String sql = "DELETE FROM messages WHERE title = ?"; stmt = conn.prepareStatement(sql); stmt.setString(1, title); int rowsDeleted = stmt.executeUpdate(); if (rowsDeleted > 0) { response.getWriter().println("Message deleted successfully"); } else { response.getWriter().println("No message found with the title " + title); } } catch (SQLException | ClassNotFoundException e) { e.printStackTrace(); response.getWriter().println("Error deleting message: " + e.getMessage()); } finally { try { if (stmt != null) { stmt.close(); } if (conn != null) { conn.close(); } } catch (SQLException e) { e.printStackTrace(); } } } } ``` 在上面的代码中,我们首先从请求中获取要删除的留言的标题,然后使用 JDBC 连接到 MySQL 数据库,并执行一个 DELETE SQL 语句,以删除具有指定标题的留言。在删除操作完成后,我们向客户端发送一条消息,指示操作是否成功。 请注意,这只是一个示例代码,您需要根据您的具体需求进行修改。您需要替换 `DB_URL`、`DB_USER` 和 `DB_PASSWORD` 常量的值,以反映您的数据库连接参数。同样,您需要在您的表中使用正确的列名来代替 `messages` 表和 `title` 列。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值