当我通过jsp页面上传文件时,servlet只显示文件名,当我们通过eclipse在ubuntu 14.04中运行时,它不会获得整个文件路径。我们如何获得文件的完整路径
这是我的部分代码。我想在servlet中获取fname中的完整路径
-----------------Servlet Code---------------------------
/************************************************************/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// checks if the request actually contains upload file
HttpSession session = request.getSession();
String uname=session.getAttribute("username").toString();
if(ServletFileUpload.isMultipartContent(request))
{
try
{
String name=null,name1=null;
String fname = null;
List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for(FileItem item : multiparts) {
if(!item.isFormField()) {
name=item.getName();
fname = new File(item.getName()).getName();
}
}
}
}
-----------------JSP code---------------------------
/************************************************************/
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>File Upload Demo</title>
</head>
<body>
<center>
<form method="post" action="uploadFile" enctype="multipart/form-data">
Select file to upload:
<input type="text" name="username" value="${uname}"/>
<input type="file" name="uploadFile"/>
<br/><br/>
<input type="submit" value="Upload"/>
</form>
</center>
</body>
答案 0 :(得分:0)
-----------------Servlet Code---------------------------
/************************************************************/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// checks if the request actually contains upload file
HttpSession session = request.getSession();
String uname=session.getAttribute("username").toString();
if(ServletFileUpload.isMultipartContent(request))
{
try
{
String name=null,name1=null;
String fname = null;
List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for(FileItem item : multiparts) {
if(!item.isFormField()) {
name=item.getName();
fname = new File(item.getName()).getAbsolutePath();
}
}
}
}
///现在你的fname将包含文件路径