如何使用jsp / servlet保存图像时设置路径?

时间:2014-02-19 05:43:08

标签: java jsp servlets

signup.jsp:这里无法设置路径将我上传的图像保存在文件夹中????提前感谢!! !!一切都很好,evrything工作正常,但图像路径显示错误。

<!DOCTYPE html>
<html lang="en">
<head>
<base href="<%=basePath%>">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Interactive Demos</title>
<link rel="stylesheet" href="css/style.css" type="text/css"/


</head>

<body>
<header>
<jsp:include page="header1.jsp"/>


</header>
<!--start mainwrap-->
<div id="mainwrap">

<!--start midwrap-->
<div id="midwrap">

<table style="width:100%; border:0; border-collapse: collapse; padding:0px;">
  <!-- <tr>
    <td style="width:74%; vertical-align:top;">&nbsp;</td>
    <td style="width:26%; ">&nbsp;</td>
  </tr> -->

   <h1 style="padding-top:6px; font-family: Palatino Linotype;  font-size:25px; font-weight:bold; color:#476aba; border-bottom:2px solid #476aba">Registration</h1>

  <tr>
    <td style="vertical-align:top;">
    <div class="lf" style="width:500px; margin-left: 240px;">
    <!-- <div style="font-size: 25px"> -->

   <!--  </div> -->
    <div class="tp-btm">

    <div style="border-radius:7px; border:1px solid black; background-color: #e7ebf5; padding-top:15px; padding-bottom:15px;">

    <form name = "frmRegistration"  id="frmRegistration"  onsubmit="submitAlbum()" method="post"  enctype="multipart/form-data">
    <table style="width:100%; text-align:center; border:0; border-collapse: collapse; padding:0px; text-align:center;">




  <tr>
    <td class="text">&nbsp;</td>
    <td style="height:40; text-align:left;" class="text">E-mail :<span class="red">*</span></td>
    <td>&nbsp;</td>
    <td><input type="email" name="email" id="email" size="25" required="required" onmouseout=""  placeholder="Eg: admin@bdisys.com"  pattern="[^@]+@[^@]+\.[a-zA-Z]{2,6}" /></td>
  </tr>





  <tr>
    <td class="text">&nbsp;</td>
    <td style="height: 40" class="text"></td>
    <td>&nbsp;</td>
    <td style="text-align: center; padding-right: 25px;"><input type="checkbox" name="imgstatus" id="imgstatus" onclick="showFileUpload();">Click Here To Set Default Image </td>
  </tr>


  <tr>
    <td class="text">&nbsp;</td>
    <td style="height: 40" class="text">Upload Image :<span class="red">*</span></td>
    <td>&nbsp;<input type="hidden" value="images/blogs.png" name="defaultimg" id="defaultimg"> </td>
    <td style="text-align: center; padding-left: 50px;"><input type="file" name="datafile" id="datafile" size="42" required="required"
                            onchange="checkFilesExtention(this);" accept='image/png,image/jpg,image/gif,image/jpeg,image/bmp,image/x-eps'>
    </td>
  </tr>

  <tr>
    <td class="text">&nbsp;</td>
    <td style="height:32;" class="text">&nbsp;</td>
    <td>&nbsp;</td>
    <td style="text-align:left; padding-left:50px; padding-top:20px;"><input type="image"  class="ab" src="images/submiit.png"/></td>
  </tr>
 </table>
</form>

</div>
    </div>
    </div></td>
    </tr>
  <tr>
    <td style="height:5;" colspan="2"></td>
  </tr>
</table>
</div>
<!--end midwrap-->
</div>
<!--end mainwrap-->

<footer>
<jsp:include page="footer1.jsp"/>
</footer>

</body>
</html>

Servlet.java:我想知道如何设置此路径???提前感谢您的帮助!!

public class signUpServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private String webTempPath;
    private String filename;

//  String server_url="http://localhost:8080/BDI Systems/";
    private static Properties properties;

    private static String filePath = MailSenderDAO.class.getResource("").getPath().replaceAll("%20", " ");
static {
try {
    properties = new Properties();
    properties.load(new FileInputStream(filePath + "/mail.config"));
} catch (Exception ex) {
//  ex.printStackTrace();
}
}
public void init(){
     webTempPath = getServletContext().getRealPath("/")+"images/";
    }

    public signUpServlet() {
        super();
        // TODO Auto-generated constructor stub
    }


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }


    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session =request.getSession();
        UserDao userDao=new UserDaoImpl();
        System.out.println("Inside SignUp Servlet===============");
        String formIdentity=request.getParameter("formidentity");//activateaccount
        System.out.println("FormIdentity================"+formIdentity);

        if(formIdentity.equalsIgnoreCase("doRegistration"))
        {
//          System.out.println("Inside doRegistration===================="+properties.getProperty("server_url"));

            String checkboxStatus=request.getParameter("checkboxStatus");
             System.out.println("status...."+checkboxStatus);
             MultipartRequest mpr = null;
             Throwable e;
            if(checkboxStatus.equalsIgnoreCase("No"))
            {
                     mpr=new MultipartRequest(request,webTempPath,5*1024*1024,new MnthFileRenamePolicy());
                    response.setContentType("text/html");
                    System.out.println("inside add details..");
                 try{


                          System.out.println("in datafile con of  servlet...");

                          this.filename=mpr.getFilesystemName("datafile");


                          File srcFile=new File(webTempPath+this.filename); 
                          System.out.println("  web temp=="+webTempPath);
                          System.out.println("image path==="+webTempPath+this.filename);

                          mpr.copyFile(srcFile, new File(webTempPath+this.filename));
                          String imgpath="images/"+this.filename;
                          System.out.println("image is=="+imgpath);
                          System.out.println("After file of  servlet...");

                          User user=new User();
                          user.setFirstName(mpr.getParameter("fname"));
                          user.setLastName(mpr.getParameter("lname"));
                          user.setEmail(mpr.getParameter("email"));
                          user.setDesc(mpr.getParameter("desc"));
                          user.setProfession(mpr.getParameter("profession"));
                          user.setDateofbirth(mpr.getParameter("dob"));
                          user.setLocation(mpr.getParameter("location"));
                          user.setProjects(mpr.getParameter("myprojects"));
                          user.setHobbies(mpr.getParameter("myhobbies")); 
                          user.setImagePath(imgpath);

                          user.setPassword(SecurityManager.asyEncrypt(mpr.getParameter("password")));
                          user.setUserStatus(Status.UNBLOCKED);
                          user.setUserType(UserType.NORMAL);
                          user.setCreatedOn(new Date());



                           User createduser=userDao.createUser(user);
                           System.out.println("hi this is temp..."+temp);
                           if(createduser==null){
                              System.out.println("hi this is ...");
                              response.sendRedirect("Registration?status=exist");
                       }


                    }


                    catch(Exception e1){
                              e1.printStackTrace();

                    }
                    finally
                    {
                        userDao.closeSession();
                    }
                }

                 else 
                 if (checkboxStatus.equalsIgnoreCase("Yes"))
                 {

                     System.out.println("in datafile con of  servlet...");

                    try{

                              User user=new User();
                              user.setFirstName(request.getParameter("fname"));
                              user.setLastName(request.getParameter("lname"));
                              user.setEmail(request.getParameter("email"));
                              user.setDesc(request.getParameter("desc"));
                              user.setProfession(request.getParameter("profession"));
                              user.setDateofbirth(request.getParameter("dob"));
                              user.setLocation(request.getParameter("location"));
                              user.setProjects(request.getParameter("myprojects"));
                              user.setHobbies(request.getParameter("myhobbies"));
                              user.setImagePath(request.getParameter("defaultimg"));
                              user.setPassword(SecurityManager.asyEncrypt(request.getParameter("password")));
                              user.setUserStatus(Status.UNBLOCKED);
                              user.setUserType(UserType.NORMAL);
                              user.setCreatedOn(new Date());
                              System.out.println("in try con of  servlet...");




                              User createduser=userDao.createUser(user);
                              if(createduser==null){
                                 response.sendRedirect("Registration?status=exist");
                              }



                        }   
                    catch(Exception e1){
                        e1.printStackTrace();

                    }finally{
                        userDao.closeSession();
                    }
                 }

        }

}

1 个答案:

答案 0 :(得分:0)

首先定义相对于保存上传图像的目录的名称 Web应用程序目录:

private static final String SAVE_DIRECTORY = "images";

然后定义保存路径并创建目录(如果该目录不存在):

String absolutePath = request.getServletContext().getRealPath("");
String savePath = appPath + File.separator + SAVE_DIRECTORY;

File imageSaveDirectory = new File(savePath);
if (!imageSaveDirectory.exists()) {
    imageSaveDirectory.mkdir();
}