2015-01-19 6 views
0

Когда я использую request.getParameter («txtPhoto»); он возвращает имя файла (image.jpg), но я хочу получить полное имя пути (C: \ Images \ image.jpg), потому что мне нужно, чтобы это полное место для сохранения файла в базе данных MySQL. Я надеюсь, что вы можете мне помочь.Java Servlet и JSP, Как получить полный путь от файла?

----------------------- страница JSP

<html> 
    <head> 
     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
     <title>Upload</title> 
    </head> 
     <body> 
      <form action="ImageController" method="post"> 
       <h1>File</h1> 
       <input type="file" name="txtPhoto" placeholder="Upload Your Image" accept="image/gif, image/jpeg, image/png" /><br /><br /> 
       <input type="submit" value="Save"> 
      </form> 
     </body> 
</html> 

-------------- --- Сервлет

@WebServlet(name = "ImageController", urlPatterns = {"/ImageController"}) 
public class imagenservlet extends HttpServlet 

{ 
    protected void processRequest(HttpServletRequest request, HttpServletResponse response) 
      throws ServletException, IOException 
    {    
     if(request.getParameter("txtPhoto") == null) 
     { 
      response.sendRedirect("upload.jsp"); 
      return; 
     } 
     PrintWriter out = response.getWriter(); 

     FileInputStream input = null; 
     File theFile = new File(request.getParameter("txtPhoto")); 
     input = new FileInputStream(theFile); 
     out.println("FullPathname" + " " + theFile.getAbsolutePath()); 

    } 
} 
+0

вы должны сделать папку Изображения внутри вашего проекта directory.Then выбрать изображение оттуда так, то вы знаете, путь, т. е. ваш-projectpath/Images/myimage.jpg – silentprogrammer

ответ

2

Вы не можете получить локальный путь к файлу, потому что он бесполезен на стороне сервера. Это было бы полезно только для хакеров. Вот почему браузеры не отправляют его.

+0

well said @Null – greenhorn

0

объявить скрытым filePath vairable на стороне JSP, назначьте свой необходимый путь к этой скрытой переменной и получите это в сервлете, он просто работает.

0

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
 
<%@ page language="java" contentType="text/html; charset=UTF-8" 
 
\t pageEncoding="UTF-8"%> 
 
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%> 
 
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> 
 

 
<html lang="en"> 
 
<head> 
 
<meta http-equiv="X-UA-Compatible" content="IE=edge"> 
 
    <meta name="viewport" content="width=device-width, initial-scale=1"> 
 
    <meta name="description" content=""> 
 
    <meta name="author" content=""> 
 
    <title>APMC Junagadh</title> 
 
    
 
    <!-- Bootstrap Core CSS --> 
 
    <link href="<c:url value='/resources/css/bootstrap.min.css' />" rel="stylesheet" /> 
 

 
    <!-- MetisMenu CSS --> 
 
    <link href="<c:url value='/resources/css/metisMenu.min.css' />" rel="stylesheet" /> 
 

 
    <!-- Custom CSS --> 
 
    <link href="<c:url value='/resources/css/sb-admin-2.css' />" rel="stylesheet" /> 
 

 
    \t <!-- Custom Fonts --> 
 
    <link href="<c:url value='/resources/css/font-awesome.min.css' />" rel="stylesheet" /> 
 

 
    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> 
 
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> 
 
    <!--[if lt IE 9]> 
 
     <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> 
 
     <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script> 
 
    <![endif]--> 
 
    
 
</head> 
 

 
<body> 
 

 
\t \t <c:choose> 
 
\t \t \t <c:when test="${empty editDistrict}"> 
 
\t \t \t \t <c:set var="action" value="${pageContext.request.contextPath}/Admin/admin/district_add" /> 
 
\t \t \t \t <c:set var="caption" value="Save" /> \t \t \t 
 
\t \t \t </c:when> 
 
\t \t \t <c:otherwise> 
 
\t \t \t \t <c:set var="action" value="${pageContext.request.contextPath}/Admin/admin/district_update" /> 
 
\t \t \t \t <c:set var="caption" value="Update" /> 
 
\t \t \t </c:otherwise> \t \t \t \t 
 
\t \t </c:choose> 
 
\t \t 
 
\t \t <div align="right"> <a href="<c:url value="/j_spring_security_logout" />" >Logout</a> </div> 
 
\t \t 
 
\t \t <div class="container"> 
 
     <div class="row"> 
 
      <div class="col-md-4 col-md-offset-4"> 
 
\t \t \t \t 
 
       <div class="panel panel-primary"> 
 
\t \t \t \t  \t \t 
 
\t \t \t \t  <div class="panel-heading"> 
 
         <h3 class="panel-title">District Name</h3> 
 
        </div> 
 
        
 
        <c:if test="${!empty successMsg}"> 
 
\t \t \t \t \t <div class="alert alert-success"> 
 
\t \t \t \t \t \t ${successMsg} 
 
\t \t \t \t \t </div> 
 
\t \t \t \t \t </c:if> 
 
\t \t \t \t \t 
 
\t \t \t \t \t <c:if test="${!empty errorMsg}"> 
 
\t \t \t \t \t <div class="alert alert-danger"> 
 
\t \t \t \t \t \t ${errorMsg} 
 
\t \t \t \t \t </div> 
 
\t \t \t \t \t </c:if> 
 
\t \t 
 
\t \t <form:form id="registerDistrictForm" modelAttribute="district" method="post" 
 
\t \t \t \t action="${action}"> 
 
\t \t <div class="panel-body"> 
 
\t \t \t 
 
\t \t \t <fieldset> 
 
\t \t \t \t <div class="form-group"> 
 
\t \t \t \t \t <label></label> 
 
\t \t \t \t </div> 
 
       <div class="form-group"> 
 
       \t <form:errors path="dst_state_id.state_id" cssClass="control-label" for="inputError" /> 
 
        \t <form:select path="dst_state_id.state_id" size="1" class="form-control"> 
 
    \t \t \t \t \t \t \t 
 
    \t \t \t \t \t \t <option value="null">Select State Name</option> \t \t \t 
 
\t  \t \t \t \t \t <c:forEach var="theState" items="${listOfstate}"> \t 
 
\t  \t \t \t \t \t \t  \t \t \t \t 
 
\t  \t \t \t \t \t \t <c:choose> 
 
\t  \t \t \t \t \t \t \t <c:when test="${theState.state_id == editDistrict.getDst_state_id().getState_id()}"> 
 
\t  \t \t \t \t \t \t \t \t 
 
\t  \t \t \t \t \t \t  \t <c:set var="selected" value="selected"/> 
 
\t  \t \t \t \t \t \t  </c:when> 
 
\t  \t \t \t \t \t \t  <c:otherwise> 
 
\t  \t \t \t \t \t \t  \t <c:set var="selected" value=""/> 
 
\t  \t \t \t \t \t \t  </c:otherwise> 
 
\t  \t \t \t \t \t \t </c:choose> \t 
 
\t  \t \t \t \t \t \t  \t \t \t \t \t \t  \t \t \t \t \t \t \t 
 
\t   \t \t \t \t \t \t <form:option value="${theState.state_id}" selected="${selected}"> 
 
\t   \t \t \t \t \t \t \t <c:out value="${theState.state_name}" /> 
 
\t   \t \t \t \t \t \t </form:option> 
 
\t   \t \t \t \t \t \t 
 
\t  \t \t \t \t \t \t </c:forEach> 
 
\t  \t \t \t \t \t \t  \t \t \t \t \t \t \t \t \t 
 
\t \t \t \t \t \t </form:select> 
 
       </div> 
 
       <div class="form-group"> 
 
       \t <form:errors path="dst_name" cssClass="control-label" for="inputError" /> 
 
        <form:input class="form-control" placeholder="District Name" path="dst_name" value="${editDistrict.dst_name}" autofocus="true" /> 
 
       </div> 
 
\t \t \t <!-- Change this to a button or input when using this as a form --> 
 
      </fieldset> 
 
     </div> 
 
\t \t <div class="panel-footer"> 
 
\t \t \t \t \t \t 
 
         \t <input type="hidden" name="dst_id" value = "${editDistrict.getDst_id()}" /> 
 
        \t <input type="submit" value="${caption}" class="btn btn-lg btn-success btn-block" /> 
 
        </div> 
 
        </form:form> 
 
       </div> 
 
      </div> 
 
     </div> \t \t  
 
\t \t \t \t 
 
\t <!-- /.row --> 
 
      <div class="row"> 
 
       <div class="col-lg-12"> 
 
        <div class="panel panel-primary"> 
 
         <div class="panel-heading"> 
 
          District List 
 
         </div> 
 
         <!-- /.panel-heading --> 
 
         <div class="panel-body"> 
 
          <div class="dataTable_wrapper"> 
 
          \t <c:if test="${!empty showDistrictList}"> 
 
           
 
           <table class="table table-striped table-bordered table-hover" id="dataTables-example"> 
 
            <thead> 
 
             <tr> 
 
\t \t \t \t \t \t \t \t \t \t \t <th> Sr. No. </th> 
 
              <th> State Name </th> 
 
              <th> District Name </th> 
 
              <th>Edit</th> 
 
             </tr> 
 
            </thead> 
 
            <tbody> 
 
            \t 
 
            <c:set var="i" value="0" /> 
 
\t \t \t \t \t \t \t \t \t <c:forEach items="${showDistrictList}" var="dst"> 
 
\t \t \t 
 
\t \t \t \t \t \t \t \t \t \t <c:set var="i" value="${i+1}" /> 
 
             <tr class="odd"> 
 
             \t <td><c:out value="${i}" /></td> 
 
             \t <td><c:out value="${dst.getDst_state_id().getState_name()}" /> 
 
\t \t \t \t \t \t \t \t \t \t \t </td> 
 
\t \t \t \t \t \t \t \t \t \t \t <td><c:out value="${dst.dst_name}" /> 
 
\t \t \t \t \t \t \t \t \t \t \t </td> 
 
\t \t \t \t \t \t \t \t \t \t \t <td><form action="${pageContext.request.contextPath}/Admin/admin/district_edit" method="post"> 
 
\t \t \t \t \t \t \t \t \t \t \t \t <input type="hidden" name ="dst_id" value="${dst.dst_id}" /> 
 
\t \t \t \t \t \t \t \t \t \t \t \t <input type="submit" value="" class="fa fa-pencil" /> 
 
\t \t \t \t \t \t \t \t \t \t \t \t </form> 
 
\t \t \t \t \t \t \t \t \t \t \t </td> 
 
             </tr> 
 
             
 
            </c:forEach> 
 
            </tbody> 
 
           </table> 
 
           </c:if> 
 
          </div> 
 
          <!-- /.table-responsive --> 
 
         </div> 
 
         <!-- /.panel-body --> 
 
        </div> 
 
        <!-- /.panel --> 
 
       </div> 
 
       <!-- /.col-lg-12 --> 
 
      </div> 
 
      <!-- /.row --> 
 
    </div> 
 

 
    <!-- jQuery --> 
 
    <script src="<c:url value="/resources/js/jquery.min.js" />"></script> 
 

 
    <!-- Bootstrap Core JavaScript --> 
 
    <script src="<c:url value="/resources/js/bootstrap.min.js" />"></script> 
 

 
    <!-- Metis Menu Plugin JavaScript --> 
 
    <script src="<c:url value="/resources/js/metisMenu.min.js" />"></script> 
 

 
\t <!-- DataTables JavaScript --> 
 
\t <script src="<c:url value="/resources/js/jquery.dataTables.min.js" />"></script> 
 
\t <script src="<c:url value="/resources/js/dataTables.bootstrap.min.js" />"></script> 
 
\t 
 
    <!-- Custom Theme JavaScript --> 
 
    <script src="<c:url value="/resources/js/sb-admin-2.js" />"></script> 
 

 
\t <!-- Page-Level Demo Scripts - Tables - Use for reference --> 
 
    <script> 
 
\t \t $(document).ready(function() { 
 
\t \t \t $('#dataTables-example').DataTable({ 
 
\t \t \t \t \t responsive: true 
 
\t \t \t }); 
 
\t \t }); 
 
    </script> 
 
\t 
 
</body> 
 

 
</html>

В вышеописанном файле district.jsp

<c:set var="action" value="${pageContext.request.contextPath}/Admin/admin/district_add" />

Этот тег я давал абсолютный путь в

<form:form action="${action}">

В рамках Я дал вам пример, что Controler

package com.apmc.controller; 
 

 
import java.text.DateFormat; 
 
import java.text.SimpleDateFormat; 
 
import java.util.ArrayList; 
 
import java.util.Date; 
 
import java.util.List; 
 

 
import javax.validation.Valid; 
 

 
import org.apache.log4j.Logger; 
 
import org.hibernate.exception.ConstraintViolationException; 
 
import org.springframework.beans.factory.annotation.Autowired; 
 
import org.springframework.beans.propertyeditors.CustomDateEditor; 
 
import org.springframework.stereotype.Controller; 
 
import org.springframework.validation.BindingResult; 
 
import org.springframework.web.bind.WebDataBinder; 
 
import org.springframework.web.bind.annotation.InitBinder; 
 
import org.springframework.web.bind.annotation.ModelAttribute; 
 
import org.springframework.web.bind.annotation.RequestMapping; 
 
import org.springframework.web.bind.annotation.RequestMethod; 
 
import org.springframework.web.bind.annotation.RequestParam; 
 
import org.springframework.web.servlet.ModelAndView; 
 

 
import com.apmc.Generic.RandomGenerator; 
 
import com.apmc.domain.District; 
 
import com.apmc.domain.State; 
 
import com.apmc.services.DistrictService; 
 
import com.apmc.services.StateService; 
 

 
@Controller 
 
public class DistrictController { 
 
\t 
 
\t private static Logger logger = Logger.getLogger(DistrictController.class); 
 
\t DateFormat df = new SimpleDateFormat("ddMMyyHHmmss"); 
 
\t Date dateobj = new Date(); 
 
\t int randNum = RandomGenerator.randInt(1000, 9999); 
 
\t String errorcode = null; 
 
\t String errorMsg = ""; 
 
\t String successMsg = ""; 
 
\t District editDistrict = null; 
 
\t List<District> newList = new ArrayList(); 
 
\t List<State> listOfstate = new ArrayList<State>(); 
 
\t 
 
\t @Autowired 
 
\t DistrictService districtService; 
 

 
\t @Autowired 
 
\t StateService stateService; 
 
\t 
 
\t @InitBinder  
 
\t public void initBinder(WebDataBinder binder){ 
 
\t  binder.registerCustomEditor(Date.class,  
 
\t       new CustomDateEditor(new SimpleDateFormat("dd/MM/yyyy"), true, 10)); 
 
\t } 
 
\t 
 
\t @RequestMapping(value = "/Admin/admin/NewDistrict_form") 
 
\t public ModelAndView districtForm(@ModelAttribute District district) { 
 
\t \t 
 
\t \t try { 
 
\t \t \t logger.info("\n districtForm Started"); 
 
\t \t \t listOfstate = stateService.loadAll(); 
 
\t \t \t newList = districtService.loadAll(); 
 
\t \t \t logger.info("\n districtForm Completed"); 
 
\t \t \t errorMsg = ""; 
 
\t \t } 
 
\t \t catch (Exception e) { 
 
\t \t \t errorcode = ""+df.format(dateobj)+randNum; 
 
\t \t \t errorMsg = " New District Form Error \n Please contact Admin and errorcode: "+errorcode; 
 
\t \t \t successMsg = ""; 
 
\t \t \t logger.error("error code for districtForm in DistrictController "+df.format(dateobj)+" errorcode: "+errorcode); 
 
\t \t } 
 
\t \t return new ModelAndView("district").addObject("editDistrict", null).addObject("errorMsg", errorMsg) 
 
\t \t \t \t  \t \t \t \t \t \t \t \t .addObject("showDistrictList", newList).addObject("successMsg", successMsg).addObject("listOfstate",listOfstate); 
 
\t } 
 

 
\t @RequestMapping(value={"/Admin/admin/district_add", "/Admin/admin/district_update"}, method=RequestMethod.POST) 
 
\t public ModelAndView saveOrUpdateDistrict(@Valid District district, BindingResult result) { 
 
\t \t 
 
\t \t if (result.hasErrors()) { 
 
\t \t \t successMsg = ""; 
 
\t \t \t errorMsg = "Data is remaining or wrong."; 
 
\t \t \t if(district.getDst_id() != null) 
 
\t \t \t \t editDistrict = district; 
 
\t \t \t else 
 
\t \t \t \t editDistrict = null; 
 
\t \t \t 
 
\t \t \t try{ 
 
\t \t \t \t listOfstate = stateService.loadAll(); 
 
\t \t \t \t newList = districtService.loadAll(); 
 
\t \t \t } catch (Exception e) { 
 
\t \t \t \t logger.error(e.getMessage()); 
 
\t \t \t \t errorcode = ""+df.format(dateobj)+randNum; 
 
\t \t \t \t successMsg = ""; 
 
\t \t \t \t errorMsg = " District Form Save or Update Error \n Please contact Admin and errorcode: "+errorcode; 
 
\t \t \t \t logger.error("error code for saveOrUpdateDistrict in DistrictController "+df.format(dateobj)+" errorcode: "+errorcode); 
 
\t \t \t } 
 
\t \t \t 
 
\t \t \t return new ModelAndView("district").addObject("editDistrict", editDistrict).addObject("errorMsg", errorMsg) 
 
\t \t \t \t \t \t \t \t \t \t \t \t \t .addObject("showDistrictList", newList).addObject("successMsg", successMsg).addObject("listOfstate",listOfstate); 
 
     } 
 
\t \t else { 
 
\t \t \t 
 
\t \t \t try { 
 
\t \t \t \t logger.info("\n saveOrUpdateDistrict Started \n errorcode : "+errorcode); 
 
\t \t \t \t districtService.saveOrUpdate(district); 
 
\t \t \t \t successMsg = "Saved Successfully"; 
 
\t \t \t \t errorMsg = ""; 
 
\t \t \t \t logger.info("\n saveOrUpdateDistrict Completed"); 
 
\t \t \t } catch(ConstraintViolationException e){ 
 
\t \t \t \t logger.error(e.getMessage()); 
 
\t \t \t \t successMsg = ""; 
 
\t \t \t \t errorMsg = "Duplicate District Name inserted"; 
 
\t \t \t } catch(Exception e){ 
 
\t \t \t \t logger.error(e.getMessage()); 
 
\t \t \t \t errorcode = ""+df.format(dateobj)+randNum; 
 
\t \t \t \t successMsg = ""; 
 
\t \t \t \t errorMsg = " District Form Save or Update Error \n Please contact Admin and errorcode: "+errorcode; 
 
\t \t \t \t logger.error("error code for saveOrUpdateDistrict in DistrictController "+df.format(dateobj)+" errorcode: "+errorcode); 
 
\t \t \t } 
 
\t \t \t try{ 
 
\t \t \t \t listOfstate = stateService.loadAll(); 
 
\t \t \t \t newList = districtService.loadAll(); 
 
\t \t \t } catch (Exception e) { 
 
\t \t \t \t logger.error(e.getMessage()); 
 
\t \t \t \t errorcode = ""+df.format(dateobj)+randNum; 
 
\t \t \t \t successMsg = ""; 
 
\t \t \t \t errorMsg = " District Form Save or Update Error \n Please contact Admin and errorcode: "+errorcode; 
 
\t \t \t \t logger.error("error code for saveOrUpdateDistrict in DistrictController "+df.format(dateobj)+" errorcode: "+errorcode); 
 
\t \t \t } 
 
\t \t \t 
 
\t \t \t if(errorMsg == "") 
 
\t \t \t \t return new ModelAndView("redirect:/Admin/admin/NewDistrict_form"); 
 
\t \t \t else 
 
\t \t \t \t return new ModelAndView("district").addObject("editDistrict", null).addObject("errorMsg", errorMsg) 
 
\t \t \t \t \t \t \t \t \t \t \t \t \t \t .addObject("showDistrictList", newList).addObject("successMsg", successMsg).addObject("listOfstate",listOfstate); 
 
\t \t } 
 
\t \t 
 
\t } 
 
\t 
 
\t @RequestMapping(value = "/Admin/admin/district_edit", method=RequestMethod.POST) 
 
\t public ModelAndView editDistrict(@RequestParam Long dst_id, @ModelAttribute District district) { 
 
\t \t 
 
\t \t errorMsg = ""; 
 
\t \t successMsg = ""; 
 
\t \t District editDistrict = new District(); 
 
\t \t try { 
 
\t \t \t \t logger.info("\n editDistrict Started \n errorcode : "+errorcode); 
 
\t \t \t \t editDistrict = districtService.get(dst_id); 
 
\t \t \t \t newList = districtService.loadAll(); 
 
\t \t \t \t logger.info("\n editDistrict Completed"); 
 
\t \t } 
 
\t \t catch (Exception e){ 
 
\t \t \t logger.error(e.getMessage()); 
 
\t \t \t errorcode = ""+df.format(dateobj)+randNum; 
 
\t \t \t errorMsg = " District Form Edit Error \n Please contact Admin and errorcode: "+errorcode; 
 
\t \t \t logger.error("error code for editDistrict in DistrictController "+df.format(dateobj)+" errorcode: "+errorcode); 
 
\t \t } 
 
\t \t System.out.println("\n\n\n\n error msg "+errorMsg); 
 
\t \t return new ModelAndView("district").addObject("editDistrict", editDistrict).addObject("showDistrictList", newList) 
 
\t \t \t \t \t \t \t \t \t \t \t \t     .addObject("errorMsg", errorMsg).addObject("listOfstate",listOfstate); 
 
\t } 
 
\t 
 
}

Смежные вопросы