Servlet文件上传:图像文件在上传目录中向文件名添加长号

时间:2017-04-22 21:40:22

标签: jsp servlets file-upload

我正在设置一个简单的本地网页,其中涉及将图像上传到本地计算机上的文件位置。我遇到的问题是,当文件保存到该位置时,它会在文件名末尾添加一个长号。我有保存到本地sql服务器的路径,所以这不起作用,任何人都可以告诉我如何使用名称上传的文件没有长号?

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    PrintWriter out = response.getWriter();

    FileItemFactory itemFactory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(itemFactory);
    upload.setHeaderEncoding("UTF-8");

    try {
        List<FileItem> items = upload.parseRequest(new ServletRequestContext(request));

        for (FileItem item : items) {
            response.setContentType("text/html");
            String contentType = item.getContentType();
            String fileName = item.getName();
            String fieldName = item.getFieldName();
            String title = item.getName();
            String[] parts =  fileName.split("\\\\");
            fileName = parts[parts.length-1];

            if (!contentType.equals("image/png")) {
                request.setAttribute("message", "Only png format image files supported");
                request.getRequestDispatcher("/loggedInUser.jsp").forward(request, response);
            } else {
                File uploadDir = new File("C:\\Users\\dholmes\\workspace\\Upload");

                File file = File.createTempFile(fileName, ".png", uploadDir);
                item.write(file);

                request.setAttribute("message", fileName + " uploaded.");
                request.getRequestDispatcher("/loggedInUser.jsp").forward(request, response);
            }
        }

    } catch (FileUploadException e) {
        e.printStackTrace();
    } 

所以对于以下示例会发生什么,我上传了一个名为Crest.png的文件,整个过程都很好,但是当我去保存它的位置时,它的名称如下:Crest .png6893740195830382611

我花了好几天寻找解决方案,希望它只需要一双新眼睛!万分感谢!

0 个答案:

没有答案