在硬编码的服务器路径上上载文件Servlet

时间:2013-04-16 08:07:51

标签: java tomcat servlets fileoutputstream

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

你有什么想法为什么我不能把文件写到上面的路径上?

THX,

2 个答案:

答案 0 :(得分:0)

类似的问题和答案 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()));
// ...

答案 1 :(得分:0)

通过查看异常,表明问题是由于路径配置不当造成的 所以你可以使用

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

因为这将更加关注路径。