jsp+servlet文件上传

jsp代码如下:

<form action="addfood" name="f1" method="post" enctype="multipart/form-data">
     <table cellpadding="3px"  style="border: 2px solid #cbdced">

<tr>
     <td>菜名:</td>
     <td>
                <input type="text" name="name" id="fname" /><b style="color: red">*</b>
   </td>
</tr>
<tr>
   <td valign="top">图片:</td>
   <td>
<input type="file" id="img" name="tupian"/>
    </td>
</tr>


    </table>
</form>

 



servlet后台代码如下:

protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
String path = getServletContext().getRealPath("/");
String saveDirectory = (new StringBuilder(String.valueOf(path))).append("upload/cuisine/").toString();
int maxPostSize = 0x100000;//设置最大请求数
File directory = new File(saveDirectory);
if (!directory.exists()){
                    directory.mkdir();
   }

MultipartRequest mr = new MultipartRequest(req, saveDirectory, maxPostSize, "utf-8");
String fname = mr.getParameter("name");//取得变量
                Enumeration files = mr.getFileNames();//得到多个file
                String name = (String)files.nextElement();
File file = mr.getFile(name);
String fileName = file.getName();
                 //保存到数据库



                resp.sendRedirect("./myeatery/succeed.jsp");

}
 

 

你可能感兴趣的:(jsp,servlet)