Java Servlet 和 JSP,如何从文件中获取完整路径名?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28017956/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java Servlet and JSP, How to get full path name from a file?
提问by Raymundo Salazar
When I use the request.getParameter("txtPhoto"); it returns the name of the file (image.jpg) but I want to get the fullpathname (C:\Images\image.jpg) because I need that complete location to save the file in MySQL database. I hope you can helpme.
当我使用 request.getParameter("txtPhoto"); 它返回文件的名称 (image.jpg),但我想获取完整路径名 (C:\Images\image.jpg),因为我需要完整的位置来将文件保存在 MySQL 数据库中。我希望你能帮助我。
-----------------------JSP Page
-----------------------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>
-----------------Servlet
-----------------Servlet
@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());
}
}
回答by null
You can not get the local filepath because it is useless on the server-side. It would only be of use to hackers. That's why browsers don't send it.
您无法获取本地文件路径,因为它在服务器端没有用。它只会对黑客有用。这就是浏览器不发送它的原因。
回答by atish shimpi
declare hidden filePath
vairable at JSP side, assign your required path to that hidden variable and get that veriable in servlet, It just work around.
filePath
在 JSP 端声明隐藏变量,将所需的路径分配给该隐藏变量并在 servlet 中获得该变量,它只是解决。
回答by Divyang Upadhyay
<!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"
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" />
<!-- 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>
<c:choose>
<c:when test="${empty editDistrict}">
<c:set var="action" value="${pageContext.request.contextPath}/Admin/admin/district_add" />
<c:set var="caption" value="Save" />
</c:when>
<c:otherwise>
<c:set var="action" value="${pageContext.request.contextPath}/Admin/admin/district_update" />
<c:set var="caption" value="Update" />
</c:otherwise>
</c:choose>
<div align="right"> <a href="<c:url value="/j_spring_security_logout" />" >Logout</a> </div>
<div class="container">
<div class="row">
<div class="col-md-4 col-md-offset-4">
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">District Name</h3>
</div>
<c:if test="${!empty successMsg}">
<div class="alert alert-success">
${successMsg}
</div>
</c:if>
<c:if test="${!empty errorMsg}">
<div class="alert alert-danger">
${errorMsg}
</div>
</c:if>
<form:form id="registerDistrictForm" modelAttribute="district" method="post"
action="${action}">
<div class="panel-body">
<fieldset>
<div class="form-group">
<label></label>
</div>
<div class="form-group">
<form:errors path="dst_state_id.state_id" cssClass="control-label" for="inputError" />
<form:select path="dst_state_id.state_id" size="1" class="form-control">
<option value="null">Select State Name</option>
<c:forEach var="theState" items="${listOfstate}">
<c:choose>
<c:when test="${theState.state_id == editDistrict.getDst_state_id().getState_id()}">
<c:set var="selected" value="selected"/>
</c:when>
<c:otherwise>
<c:set var="selected" value=""/>
</c:otherwise>
</c:choose>
<form:option value="${theState.state_id}" selected="${selected}">
<c:out value="${theState.state_name}" />
</form:option>
</c:forEach>
</form:select>
</div>
<div class="form-group">
<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>
<!-- Change this to a button or input when using this as a form -->
</fieldset>
</div>
<div class="panel-footer">
<input type="hidden" name="dst_id" value = "${editDistrict.getDst_id()}" />
<input type="submit" value="${caption}" class="btn btn-lg btn-success btn-block" />
</div>
</form:form>
</div>
</div>
</div>
<!-- /.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">
<c:if test="${!empty showDistrictList}">
<table class="table table-striped table-bordered table-hover" id="dataTables-example">
<thead>
<tr>
<th> Sr. No. </th>
<th> State Name </th>
<th> District Name </th>
<th>Edit</th>
</tr>
</thead>
<tbody>
<c:set var="i" value="0" />
<c:forEach items="${showDistrictList}" var="dst">
<c:set var="i" value="${i+1}" />
<tr class="odd">
<td><c:out value="${i}" /></td>
<td><c:out value="${dst.getDst_state_id().getState_name()}" />
</td>
<td><c:out value="${dst.dst_name}" />
</td>
<td><form action="${pageContext.request.contextPath}/Admin/admin/district_edit" method="post">
<input type="hidden" name ="dst_id" value="${dst.dst_id}" />
<input type="submit" value="" class="fa fa-pencil" />
</form>
</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>
<!-- DataTables JavaScript -->
<script src="<c:url value="/resources/js/jquery.dataTables.min.js" />"></script>
<script src="<c:url value="/resources/js/dataTables.bootstrap.min.js" />"></script>
<!-- Custom Theme JavaScript -->
<script src="<c:url value="/resources/js/sb-admin-2.js" />"></script>
<!-- Page-Level Demo Scripts - Tables - Use for reference -->
<script>
$(document).ready(function() {
$('#dataTables-example').DataTable({
responsive: true
});
});
</script>
</body>
</html>
In above file district.jsp
在上面的文件 District.jsp 中
<c:set var="action" value="${pageContext.request.contextPath}/Admin/admin/district_add" />
This tag I used to give absolute path in
这个标签我用来给出绝对路径
<form:form action="${action}">
As under I gave you example for that 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 {
private static Logger logger = Logger.getLogger(DistrictController.class);
DateFormat df = new SimpleDateFormat("ddMMyyHHmmss");
Date dateobj = new Date();
int randNum = RandomGenerator.randInt(1000, 9999);
String errorcode = null;
String errorMsg = "";
String successMsg = "";
District editDistrict = null;
List<District> newList = new ArrayList();
List<State> listOfstate = new ArrayList<State>();
@Autowired
DistrictService districtService;
@Autowired
StateService stateService;
@InitBinder
public void initBinder(WebDataBinder binder){
binder.registerCustomEditor( Date.class,
new CustomDateEditor(new SimpleDateFormat("dd/MM/yyyy"), true, 10));
}
@RequestMapping(value = "/Admin/admin/NewDistrict_form")
public ModelAndView districtForm(@ModelAttribute District district) {
try {
logger.info("\n districtForm Started");
listOfstate = stateService.loadAll();
newList = districtService.loadAll();
logger.info("\n districtForm Completed");
errorMsg = "";
}
catch (Exception e) {
errorcode = ""+df.format(dateobj)+randNum;
errorMsg = " New District Form Error \n Please contact Admin and errorcode: "+errorcode;
successMsg = "";
logger.error("error code for districtForm in DistrictController "+df.format(dateobj)+" errorcode: "+errorcode);
}
return new ModelAndView("district").addObject("editDistrict", null).addObject("errorMsg", errorMsg)
.addObject("showDistrictList", newList).addObject("successMsg", successMsg).addObject("listOfstate",listOfstate);
}
@RequestMapping(value={"/Admin/admin/district_add", "/Admin/admin/district_update"}, method=RequestMethod.POST)
public ModelAndView saveOrUpdateDistrict( @Valid District district, BindingResult result) {
if (result.hasErrors()) {
successMsg = "";
errorMsg = "Data is remaining or wrong.";
if(district.getDst_id() != null)
editDistrict = district;
else
editDistrict = null;
try{
listOfstate = stateService.loadAll();
newList = districtService.loadAll();
} catch (Exception e) {
logger.error(e.getMessage());
errorcode = ""+df.format(dateobj)+randNum;
successMsg = "";
errorMsg = " District Form Save or Update Error \n Please contact Admin and errorcode: "+errorcode;
logger.error("error code for saveOrUpdateDistrict in DistrictController "+df.format(dateobj)+" errorcode: "+errorcode);
}
return new ModelAndView("district").addObject("editDistrict", editDistrict).addObject("errorMsg", errorMsg)
.addObject("showDistrictList", newList).addObject("successMsg", successMsg).addObject("listOfstate",listOfstate);
}
else {
try {
logger.info("\n saveOrUpdateDistrict Started \n errorcode : "+errorcode);
districtService.saveOrUpdate(district);
successMsg = "Saved Successfully";
errorMsg = "";
logger.info("\n saveOrUpdateDistrict Completed");
} catch(ConstraintViolationException e){
logger.error(e.getMessage());
successMsg = "";
errorMsg = "Duplicate District Name inserted";
} catch(Exception e){
logger.error(e.getMessage());
errorcode = ""+df.format(dateobj)+randNum;
successMsg = "";
errorMsg = " District Form Save or Update Error \n Please contact Admin and errorcode: "+errorcode;
logger.error("error code for saveOrUpdateDistrict in DistrictController "+df.format(dateobj)+" errorcode: "+errorcode);
}
try{
listOfstate = stateService.loadAll();
newList = districtService.loadAll();
} catch (Exception e) {
logger.error(e.getMessage());
errorcode = ""+df.format(dateobj)+randNum;
successMsg = "";
errorMsg = " District Form Save or Update Error \n Please contact Admin and errorcode: "+errorcode;
logger.error("error code for saveOrUpdateDistrict in DistrictController "+df.format(dateobj)+" errorcode: "+errorcode);
}
if(errorMsg == "")
return new ModelAndView("redirect:/Admin/admin/NewDistrict_form");
else
return new ModelAndView("district").addObject("editDistrict", null).addObject("errorMsg", errorMsg)
.addObject("showDistrictList", newList).addObject("successMsg", successMsg).addObject("listOfstate",listOfstate);
}
}
@RequestMapping(value = "/Admin/admin/district_edit", method=RequestMethod.POST)
public ModelAndView editDistrict(@RequestParam Long dst_id, @ModelAttribute District district) {
errorMsg = "";
successMsg = "";
District editDistrict = new District();
try {
logger.info("\n editDistrict Started \n errorcode : "+errorcode);
editDistrict = districtService.get(dst_id);
newList = districtService.loadAll();
logger.info("\n editDistrict Completed");
}
catch (Exception e){
logger.error(e.getMessage());
errorcode = ""+df.format(dateobj)+randNum;
errorMsg = " District Form Edit Error \n Please contact Admin and errorcode: "+errorcode;
logger.error("error code for editDistrict in DistrictController "+df.format(dateobj)+" errorcode: "+errorcode);
}
System.out.println("\n\n\n\n error msg "+errorMsg);
return new ModelAndView("district").addObject("editDistrict", editDistrict).addObject("showDistrictList", newList)
.addObject("errorMsg", errorMsg).addObject("listOfstate",listOfstate);
}
}