java.lang.IllegalStateException:文件已被移动 - 无法在Mulipart文件上传中再次读取带有JavaMail的Spring MVC

时间:2017-05-26 12:57:00

标签: java spring spring-mvc javamail

  

java.lang.IllegalStateException:文件已被移动 - 无法再次读取

我收到此异常,邮件未使用javamail发送。当只有一个附件时,它工作正常,如果上传了多个文件,它就无法正常工作。

public class SomeClass {

    @Override
    public void sendMail(EmailReportsVO report) throws Exception {
        taskExecutor.execute( new Runnable() {
            public void run() {
                try {

                    List<String> absolutePaths=new ArrayList<String>();
                    List<MultipartFile> file = report.getFile();
                    System.err.println("file size::"+report.getFile()+ " :: size is ::"+file.size());
                    if(file.size()>0){
                        for (MultipartFile mFile : file) {
                            if(mFile.getSize()>0){
                                Thread.sleep(mFile.getSize()+1000);
                                File fileData = convert(mFile);
                                String absolutePath = fileData.getAbsolutePath();
                                absolutePaths.add(absolutePath);

                            }
                        }
                    }
                    sendMailSimple(report.getMessageBody(), report.getMailTo(), report.getSubject(), absolutePaths);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public File convert(MultipartFile multipart) throws IllegalStateException, IOException, InterruptedException {
        File convFile = new File( multipart.getOriginalFilename());
        multipart.transferTo(convFile);
        return convFile;
    }

    private void sendMailSimple(String text,  String to, String subject, List<String> filePaths) throws Exception {
        MimeMessage message = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom("lottisrikanth@gmail.com");
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(text);

            if(filePaths.size()>0){
                FileSystemResource file =null;
                for (String filePath : filePaths) {
                    System.err.println("Hello path:: "+filePath);
                    file =new FileSystemResource(filePath);
 helper.addAttachment(file.getFilename(), file);
                }


            }
        } catch (MessagingException e) {
            throw new MailParseException(e);
        }
        mailSender.send(message);

    }
}

1 个答案:

答案 0 :(得分:0)

你不想在helper.addAttachment循环中调用for吗?

文件名可能还有其他错误,文件被删除后,但我无法从您提供的信息中看出来。