如何在java servlet中获取Uploaded filename?

时间:2016-09-19 20:30:15

标签: java servlets

我有这个:

public void doPost(HttpServletRequest request, 
      HttpServletResponse response) throws IOException, ServletException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    try{
        sentfilename = printNames(request);
        MultipartRequest multipartRequest = new MultipartRequest(request, ImageDirecoty, 1024*1024*5);
    } catch(IOException e){
        response.sendError(HttpServletResponse.SC_CONFLICT, "File limit has exceeded or it wasn't an actual image");
        System.out.println(e.getMessage());
        return;
    }
}

public String printNames(HttpServletRequest request) throws IOException, ServletException{
        for(Part part : request.getParts()){
            Collection<String> headers = part.getHeaders("content-disposition");
            if (headers == null)
                continue;
            for(String header : headers){
                String filename = header.substring(header.indexOf("filename=") + 10 , header.length());
                String result = filename.replace("\"", "");
                return result;
            } 
        }
        return null;
}

基本上我是从客户端上传一个简单文件,现在我需要从请求数据中获取文件名,这些文件可以通过printNames函数成功获取并将请求数据写入我的filepath,现在的问题是,正如您在doPost() try中看到的那样,如果我首先放置printNames函数,我可以获取文件名,但它不会写入数据,如果我放MultipartRequest首先我可以得到文件上传但我没有得到文件名。

希望不要提前混淆和感谢

1 个答案:

答案 0 :(得分:0)

你可以从零件对象本身获取它

String fileName = part.getSubmittedFileName();

示例:

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    Deque<FileInfo> files = new LinkedList<>();
    for (Part part : req.getParts()) {
        long fileSize = part.getSize();
        String fileName = part.getSubmittedFileName();
        if (fileSize == 0 && (fileName == null || fileName.isEmpty())) {
            continue; // Ignore part, if not a file.
        }
        FileInfo info = new FileInfo(UUID.randomUUID(), fileSize, fileName, part.getContentType());

        files.add(info);
        Files.copy(part.getInputStream(), new File(uploads, info.getId().toString()).toPath());
    }

    req.getSession().setAttribute("uploadedFiles", files);
    resp.sendRedirect(applicationUrl + "/upload");
}

来源:http://ursaj.com/upload-files-in-java-with-servlet-api

希望它有所帮助!