Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/402.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在JavaMail应用程序中找不到上载文件的绝对路径_Java_Servlets_Jakarta Mail - Fatal编程技术网

在JavaMail应用程序中找不到上载文件的绝对路径

在JavaMail应用程序中找不到上载文件的绝对路径,java,servlets,jakarta-mail,Java,Servlets,Jakarta Mail,我试图创建一个简单的javamail应用程序,它可以处理附件,但每当我发送电子邮件时,它都会显示“java.io.FileNotFoundException:fileName”。上传我验证过的文件没有问题,但无法提取上传文件的绝对路径。我正在使用html表单发送多部分表单数据。下面是我的java代码: [编辑]MailApp.java: @WebServlet("/EmailSendingServlet") @MultipartConfig(fileSizeThreshold=58576, ma

我试图创建一个简单的javamail应用程序,它可以处理附件,但每当我发送电子邮件时,它都会显示“java.io.FileNotFoundException:fileName”。上传我验证过的文件没有问题,但无法提取上传文件的绝对路径。我正在使用html表单发送多部分表单数据。下面是我的java代码:

[编辑]MailApp.java:

@WebServlet("/EmailSendingServlet")
@MultipartConfig(fileSizeThreshold=58576, maxFileSize=20848820, maxRequestSize=418018841)

public class MailApp extends HttpServlet {
private String host;
private String port;

private static final String SAVE_DIR = "uploadFiles";

public void init() {
    host = "smtp.gmail.com";
    port = "587";    }

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String recipient = null;
    String subject = null;
    String content = null;
    String user = null;
    String pass = null;
    String fileName = null;

 // gets absolute path of the web application
    String appPath = request.getServletContext().getRealPath("");
    // constructs path of the directory to save uploaded file
    String savePath = appPath + File.separator + SAVE_DIR;

    // creates the save directory if it does not exists
    File fileSaveDir = new File(savePath);
    if (!fileSaveDir.exists()) {
        fileSaveDir.mkdir();
    }

    for( Part p : request.getParts() ) {
        if( "uploaded_file".equals(p.getName()) ) {
             fileName = extractFileName(p);
            // refines the fileName in case it is an absolute path
            fileName = new File(fileName).getName();
            p.write(savePath + File.separator + fileName);
        }
       else if( "recipient".equals(p.getName()) ) {recipient = request.getParameter("recipient");}
       else if( "subject".equals(p.getName()) ) {subject = request.getParameter("subject");}
        if( "content".equals(p.getName()) ) {content = request.getParameter("content");}
       else if( "user".equals(p.getName()) ) {user = request.getParameter("user");}
       else if( "pass".equals(p.getName()) ) {pass =request.getParameter("pass");}

    }
String resultMessage = "";


    try {            
        SendMail.sendEmail(host, port, user, pass, recipient, subject, content, fileName);
        resultMessage = "The e-mail was sent successfully";
    } catch (Exception ex) {
        ex.printStackTrace();
        resultMessage = "There were an error: " + ex.getMessage();
    } 
    finally {
        request.setAttribute("Message", resultMessage);
        getServletContext().getRequestDispatcher("/iml.jsp").forward(
                request, response);
    }
}
private String extractFileName(Part part) {
    String contentDisp = part.getHeader("content-disposition");
    String[] items = contentDisp.split(";");
    for (String s : items) {
        if (s.trim().startsWith("filename")) {
            return s.substring(s.indexOf("=") + 2, s.length()-1);
        }
    }
    return "";
}}
SendMail.java:

public class SendMail 
{ 
   public static void sendEmail(String host, String port,
            final String userName, final String password, String toAddress,
            String subject, String message,String fileName) throws AddressException,
            MessagingException {


        // sets SMTP server properties
        Properties properties = new Properties();
        properties.put("mail.smtp.host", host);
        properties.put("mail.smtp.port", port);
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.starttls.enable", "true");

        // creates a new session with an authenticator
        Authenticator auth = new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(userName, password);
            }
        };

        Session session = Session.getInstance(properties, auth);

        // creates a new e-mail message
        Message msg = new MimeMessage(session);

        msg.setFrom(new InternetAddress(userName));
        InternetAddress[] toAddresses = { new InternetAddress(toAddress) };
        msg.setRecipients(Message.RecipientType.TO, toAddresses);
        msg.setSubject(subject);
        msg.setSentDate(new Date());

        MimeBodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setContent(message, "text/html");

        // creates multi-part
        Multipart multipart = new MimeMultipart();
        DataSource source = new FileDataSource(fileName);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(fileName);
        multipart.addBodyPart(messageBodyPart);


        // sets the multi-part as e-mail's content
        msg.setContent(multipart);

   try{     // sends the e-mail
        Transport.send(msg);
   }
   catch (Exception ex) {
       ex.printStackTrace();
   }
}
}
请帮我解决它

  • 您需要创建一个目录来保存上载的文件

  • 您需要为文件创建完整路径

  • 您需要将上载的文件写入您保存的文件,方法是:

    filePart.write(FULL_FILE_PATH);
    
  • 你可以点击链接
  • 好,, 我可能错了。。。 在保存(书写)你正在做的事情时

    p.write(savePath + File.separator + fileName);
    
    但在调用“sendEmail”时,您只发送“文件名”,
    应该改为“savePath+File.separator+fileName”吗?

    据我所知
    path.get(filePart.getSubmittedFileName()).getFileName().toString()
    is提供确切的文件名和路径。get(filePart.getSubmittedFileName())提供文件路径。让我们尝试不使用
    .getFileName.toString()
    。使用
    路径.get(filePart.getSubmittedFileName()).toString()
    ,但仍然只获取文件名。只需停止使用
    getRealPath()
    。我已验证上载文件没有问题,在发送时尝试访问同一文件时出现问题。上载文件后,我可以使用request.getparameter()作为文本参数吗?根据您的回答,我已更改了MailApp.java的代码,但我仍然得到相同的错误。请检查它。经过几次调整后找到了答案。感谢您为我指出了正确的方向。尝试了它,仍然得到相同的异常。我认为它无法提取绝对路径。好的,检查一下权限,是“SAVE_DIR”还是正在创建的文件?是的,正在创建,这里是存储文件的路径“E:\java WS\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\Mwa\\uploadFiles”。我想问题是在上传文件之前有两个“\”吗?你能检查一下这个线程,确认在你的案例中没有发生类似的事情吗?上传正常。