1

我有一个 .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。

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

谢谢,

4

2 回答 2

0

类似问答 如何使用 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()));
// ...
于 2013-04-16T08:21:39.297 回答
0

通过查看异常,表明问题是由于路径配置不正确。
所以你可以使用

File targetFile = new File(targetPath, filename) ;  // target path is hard coded for you.

因为这将更加照顾路径。

于 2013-04-16T08:25:39.220 回答