gpt4 book ai didi

java - 在硬编码的服务器路径上上传文件 Servlet

转载 作者:行者123 更新时间:2023-11-28 22:31:29 24 4
gpt4 key购买 nike

我有一个显示文件浏览器和上传按钮的 .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文件名、目录名或卷标语法不正确)。搜索这个并没有找到任何相关的东西。我不知道它是否有帮助,但我使用 Servlet 3.0 和 Apache Tomcat v7。

你知道为什么我不能把我的文件写到上面的路径吗?

谢谢,

最佳答案

类似问答 How to set the path to "context path" for uploaded files using Apache Common fileupload?

使用java.io.File

String relativeWebPath = "/WEB-INF/uploads";
String absoluteFilePath = getServletContext().getRealPath(relativeWebPath);
File uploadedFile = new File(absoluteFilePath, FilenameUtils.getName(item.getName()));
// ...

关于java - 在硬编码的服务器路径上上传文件 Servlet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16031818/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com