我有一个 .jsp 页面,它显示了一个文件浏览器和一个上传按钮以及一个应该将文件上传到服务器的 Servlet。问题是文件已上传到临时文件夹,但我需要将其上传到服务器上的特定路径,但路径无法识别。
UploadServlet:doPost 方法
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
// get access to file that is uploaded from client
Part p1 = request.getPart("file");
InputStream is = p1.getInputStream();
String filename = getFilename(p1);
// get temporary path - this works but it saves on a tmp folder...
//String outputfile = this.getServletContext().getRealPath(filename); // get path on the server
//hardcoded path on which I have to save my file
String outputfile = "http://localhost:8080/Tutorial2/Upload/" + filename;
FileOutputStream os = new FileOutputStream (outputfile);
// write bytes taken from uploaded file to target file
int ch = is.read();
while (ch != -1) {
os.write(ch);
ch = is.read();
}
os.close();
out.println("<h3>File uploaded successfully!</h3>");
}
catch(Exception ex) {
out.println("Exception -->" + ex.getMessage());
}
finally {
out.close();
}
}
private static String getFilename(Part part) {
for (String cd : part.getHeader("content-disposition").split(";")) {
if (cd.trim().startsWith("filename")) {
String filename = cd.substring(cd.indexOf('=') + 1).trim().replace("\"", "");
return filename.substring(filename.lastIndexOf('/') + 1).substring(filename.lastIndexOf('\\') + 1); // MSIE fix.
}
}
return null;
}
.jsp 页面
<form action="UploadServlet" method="post" enctype="multipart/form-data">
<table>
<tr>
<td>Select File : </td>
<td><input name="file" type="file"/> </td>
</tr>
</table>
<p/>
<input type="submit" value="Upload File"/>
</form>
我看过很多关于这个问题的帖子,但都没有帮助我。当我运行我的 servlet 时,我在FileOutputStream os = new FileOutputStream (outputfile);
-处得到一个异常Exception -->http:\localhost:8080\Tutorial2\Upload\SvnBridge.exe (The filename, directory name, or volume label syntax is incorrect)
。搜索了这个,没有找到任何相关的东西。我不知道它是否有帮助,但我使用 Servlet 3.0 和 Apache Tomcat v7。
你知道为什么我不能将我的文件写入上面的路径吗?
谢谢,