【问题标题】:How to write the file from MultipartHttpServletRequest in java如何在 java 中从 MultipartHttpServletRequest 写入文件
【发布时间】:2020-10-16 09:20:41
【问题描述】:

由于我的后端团队将发送 zip 文件,如何接收文件并存储到 java(eclipse) 中的项目位置

当我尝试使用 MultipartHttpServletRequest 并获取多部分长度和 zip 文件夹时,我尝试了一些代码,但是当无法提取时显示无效。那么如何写入文件。请帮帮我

@RequestMapping(value = "/retrieveBillerByFile1", method = RequestMethod.POST)
    public @ResponseBody void retrieveBillerByFile1(@RequestPart MultipartHttpServletRequest  request) throws Exception 
    {
        System.out.println("RESPONSEEEE**"+request);
        
            Iterator<String> itrator = request.getFileNames();
            System.out.println("File Name:" + request.getFileNames());
            MultipartFile multiFile = request.getFile(itrator.next());
            System.out.println("itrator.next()" + itrator.next());
          
            
             try {
                // just to show that we have actually received the file
                     System.out.println("File Length:" + multiFile.getBytes().length);
                  String name = multiFile.getOriginalFilename();
                System.out.println("name" + name);
                
                System.out.println("multiFile.getBytes()" + multiFile.getBytes());
                BufferedWriter w = Files.newBufferedWriter(Paths.get("D:\\cedge_uat\\" + name ));
                w.write(new String(multiFile.getBytes()));
                w.flush();

               
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                throw new Exception("Error while loading the file");
            }
        
    
}

我尝试过的另一种方法,但 fileItem 为空

@RequestMapping(value = "/retrieveBillerByFile", method = RequestMethod.POST)
    public @ResponseBody void retrieveBillerByFile(@RequestPart HttpServletRequest request,
            HttpServletResponse response) throws Exception 
    {
        System.out.println("RESPONSEEEE**"+request);
        System.out.println("request**"+request);
        
        
          // checks if the request actually contains upload file
        if (!ServletFileUpload.isMultipartContent(request)) {
            System.out.println("Form must has enctype=multipart/form-data.**");
            // if not, we stop here
            PrintWriter writer = response.getWriter();
            writer.println("Error: Form must has enctype=multipart/form-data.");
            writer.flush();
            return;
        }
 
        // configures upload settings
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // sets memory threshold - beyond which files are stored in disk
        factory.setSizeThreshold(MEMORY_THRESHOLD);
        // sets temporary location to store files
        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
 
        ServletFileUpload upload = new ServletFileUpload(factory);
         
        // sets maximum size of upload file
        upload.setFileSizeMax(MAX_FILE_SIZE);
         
        // sets maximum size of request (include file + form data)
        upload.setSizeMax(MAX_REQUEST_SIZE);
 
        // constructs the directory path to store upload file
        // this path is relative to application's directory
      //  String uploadPath = servletContext.getRealPath("")+ File.separator + UPLOAD_DIRECTORY;
         
        String uploadPath = servletContext.getRealPath("/WEB-INF/xml") + File.separator + UPLOAD_DIRECTORY;
        // creates the directory if it does not exist
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }
        System.out.println("uploadPath\n"+ uploadPath);
        try {
            // parses the request's content to extract file data
            @SuppressWarnings("unchecked")
            List<FileItem> formItems = upload.parseRequest(request);
            System.out.println("formItems**"+formItems);
            if (formItems != null && formItems.size() > 0) {
                // iterates over form's fields
                for (FileItem item : formItems) {
                    System.out.println("item**"+item);
                    // processes only fields that are not form fields
                    if (!item.isFormField()) {
                        String fileName = new File(item.getName()).getName();
                        System.out.println("fileName**"+fileName);
                        String filePath = uploadPath + File.separator + fileName;
                        File storeFile = new File(filePath);
 
                        // saves the file on disk
                        item.write(storeFile);
                        System.out.println("success");
                        request.setAttribute("message",
                            "Upload has been done successfully!");
                    }
                }
            }
        } catch (Exception ex) {
            System.out.println("exception"+ ex.getMessage());
            request.setAttribute("message",
                    "There was an error: " + ex.getMessage());
        }
        
    }

【问题讨论】:

  • 任何人请建议

标签: java file servlets multipart


【解决方案1】:

您可以在方法中添加另一个参数--

@RequestParam MultipartFile file

所以你的方法将是--

public @ResponseBody void retrieveBillerByFile1(@RequestParam MultipartFile file, @RequestPart MultipartHttpServletRequest  request) throws Exception 

然后使用java文件api来操作文件

【讨论】:

  • 你能详细解释一下,那么如何使用请求和文件。我不明白
  • 你能检查我上面的代码吗,我已经尝试了另一种方法,第一个和第二个 SOP 正在打印和
  • ,根据您的cmets,我添加并打印了file.getoriginalfilename: name**HGA1F0FA8C0000006379.zip
  • String filePath = uploadPath + File.separator + name; System.out.println("filePath" + filePath);文件目标 = 新文件(文件路径); FileOutputStream fos = new FileOutputStream(dest); fos.write(file.getBytes()); fos.close();
猜你喜欢
  • 1970-01-01
  • 2014-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-23
  • 1970-01-01
  • 2014-09-13
相关资源
最近更新 更多