0

首先,我要感谢大家发布的答案。这个网站很棒。其次,我遇到了一个问题,搜索了几天后我仍然无法弄清楚。我发现很多人有同样的问题,但没有答案。我正在尝试将图像上传到在应用程序引擎上运行的应用程序并发送带有图像作为附件的电子邮件。我也在使用 org.apache.commons.fileupload 来上传图片。我成功发送了电子邮件,但附件有问题。我的 html 表单如下所示:

<form id="contact" action="/sign" method="post" enctype="multipart/form-data">
                            <fieldset>
                                <label>Nume / Prenume</label>
                                <input type="text" name="nume" />
                                <label>Telefon</label>
                                <input type="text" name="telefon" />
                                <label>E-mail</label>
                                <input type="text" name="email"/>                                    
                            </fieldset>
                            <fieldset>
                                <label>Textul sesizarii</label>
                                <textarea name="textulses"></textarea>
                                <div class="upload-fix-wrap">
                                    <input size="35" class="upload" type="file"         name=myFile />
                                    <input type="text" />
                                    <button>Incarca poze</button>
                                </div>
                                <button class="send" type="submit">Trimite </button>
                            </fieldset>
                        </form>

我选择 wich servlet 应该回答的 web.xml 文件如下所示:

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<servlet>
    <servlet-name>sign</servlet-name>
    <servlet-class>com.campiacareiului.CampiaCareiuluiServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>sign</servlet-name>
    <url-pattern>/sign</url-pattern>
</servlet-mapping>
<welcome-file-list>
    <welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>

所以,现在我有一个 html 表单和一个 servlet 来响应。首先,我尝试使用 javax.mail:

public class CampiaCareiuluiServlet extends HttpServlet {
private String nume=null;
private String telefon=null;
private String email=null;
private String textulses=null;
private String attname=null;
private  byte[] buffer = new byte[8192000];
private boolean att=false;
private int size=0;
private static final Logger log =
          Logger.getLogger(CampiaCareiuluiServlet.class.getName());
public void doPost(HttpServletRequest req, HttpServletResponse resp)
        throws IOException {
    try {

        ServletFileUpload upload=new ServletFileUpload();
        FileItemIterator it = upload.getItemIterator(req);
        while(it.hasNext()){
            FileItemStream item = it.next();
            String name = item.getFieldName();
            InputStream stream = item.openStream();
            if (item.isFormField()) {
    if(name.equals("nume")) nume=Streams.asString(stream);
        else if(name.equals("telefon")) telefon=Streams.asString(stream);
        else if(name.equals("email")) email=Streams.asString(stream);
        else if(name.equals("textulses")) textulses=Streams.asString(stream);
            } else {
                att=true;
                attname=item.getName();

                int len;
                size=0;
               while ((len = stream.read(buffer, 0, buffer.length)) != -1){
                    size+=len;

                 }

            }

        }
          Properties props = new Properties();
            Session session = Session.getDefaultInstance(props, null);

  String msgBody = "Nume/Prenume: "+nume+" Telefon: "+telefon+" Mail:"+email+"Textul  Sesizarii: "+textulses;
  Message msg = new MimeMessage(session);
                msg.setFrom(new     InternetAddress("myAdministratorAccount@gmail.com", ""));
                msg.addRecipient(Message.RecipientType.TO,
                                 new InternetAddress("aUser@yahoo.com", "Mr. User"));
                msg.setSubject("Mail Sesizare Campia Careiului");
                msg.setText(msgBody);
   if(att){
         byte[] bufferTemp = new byte[size];
         for(int i=0;i<=size;i++)
             bufferTemp[i]=buffer[i];
             Multipart mp=new MimeMultipart();
                   MimeBodyPart attachment= new MimeBodyPart();

                   DataSource src = new ByteArrayDataSource 
                           (bufferTemp,"image/jpeg"); 
                   attachment.setFileName(attname);
                   attachment.setContent(src,"image/jpeg"); 
                   mp.addBodyPart(attachment);
                   msg.setContent(mp);

         }
     Transport.send(msg);
     resp.sendRedirect("/contact.html");
    } catch (Exception ex) {
          try {
            throw new ServletException(ex);
        } catch (ServletException e) {

            e.printStackTrace();
}
      }

}
}

当我调试应用程序时,它显示它已将图像上传到缓冲区,但发送邮件失败(未引发异常)。(我将应用程序上传到应用程序引擎,因为如果您正在运行应用程序,则无法发送电子邮件本地)。接下来我尝试使用低级 api。我所做的更改是:

                    Properties props = new Properties();
            Session session = Session.getDefaultInstance(props, null);

            String msgBody = "Nume/Prenume: "+nume+" Telefon: "+telefon+" Mail: "+email+" Textul Sesizarii: "+textulses;

            MailService service = MailServiceFactory.getMailService(); 
            MailService.Message msg = new MailService.Message(); 
                    msg.setSender("myAdminAccount@gmail.com"); 
                    msg.setTo("aUser@yahoo.com"); 
                    msg.setSubject("Mail Sesizare Campia Careiului"); 
                    msg.setTextBody(msgBody); 
     if(att){
         byte[] bufferTemp = new byte[size];
         for(int i=0;i<=size;i++)
             bufferTemp[i]=buffer[i];

            MailService.Attachment attachment=new MailService.Attachment("picture.pdf",
                   bufferTemp);
            msg.setAttachments(attachment);
             }
            service.send(msg);
                            resp.sendRedirect("/contact.html");

现在,它发送带有附件的电子邮件,但是当我尝试从我的电子邮件帐户(pdf 或图像)下载附件时,它无法识别它。它只是说文件可能已损坏。当我尝试发送图像时,我输入了“image/jpeg”,当我尝试发送 pdf 时,我输入了“application/pdf”。我到处搜索,发现其他人有这个问题,但没有解决方案。如果有人可以帮助我,我将不胜感激。(我为我的拼写错误道歉)我的进口是:

import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.Properties;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.activation.DataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMultipart;
import javax.mail.util.ByteArrayDataSource;
import javax.mail.Multipart;
import javax.servlet.http.*;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
import org.apache.commons.io.IOUtils;

import com.google.appengine.api.mail.MailService;
import com.google.appengine.api.mail.MailServiceFactory;

我使用以下代码成功发送了带有附件的电子邮件。但我的问题是,当我尝试下载附件或尝试查看它时,它说它已损坏并且无法识别。我认为问题在于上传图像。要上传图片,我使用 org.apache.commons.fileupload。在这里,我将图像上传到字节数组:

    while ((len = stream.read(buffer, 0, buffer.length)) != -1)
           {
                size+=len;
            }

我还在“大小”中跟踪上传图像的大小在这里,我将图像移动到另一个适当尺寸的缓冲区中:

            byte[] bufferTemp = new byte[size];
            for(int i=0;i<size;i++)
                bufferTemp[i]=buffer[i];

附件中的图像与上传的图像具有相同的尺寸,但不知何故损坏了。如果有人可以提供帮助。源代码是:

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMultipart;
import javax.mail.util.ByteArrayDataSource;
import javax.mail.Multipart;
import javax.servlet.http.*;

import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;


@SuppressWarnings("serial")
public class CampiaCareiuluiServlet extends HttpServlet {
private String nume=null;
private String telefon=null;
private String email=null;
private String textulses=null;
private String attname=null;
private  byte[] buffer = new byte[8192000];
private boolean att=false;
private int size=0;
private static final Logger log =
        Logger.getLogger(CampiaCareiuluiServlet.class.getName());
public void doPost(HttpServletRequest req, HttpServletResponse resp)
        throws IOException {
    try {

        ServletFileUpload upload=new ServletFileUpload();
        FileItemIterator it = upload.getItemIterator(req);
        while(it.hasNext()){
            FileItemStream item = it.next();
            String name = item.getFieldName();
            InputStream stream = item.openStream();
            if (item.isFormField()) {
                if(name.equals("nume")) nume=Streams.asString(stream);
                else if(name.equals("telefon")) telefon=Streams.asString(stream);
                else if(name.equals("email")) email=Streams.asString(stream);
                else if(name.equals("textulses")) textulses=Streams.asString(stream);
            } else {
                att=true;
                attname=item.getName();

                int len;
                size=0;
                while ((len = stream.read(buffer, 0, buffer.length)) != -1){
                    size+=len;

                }

            }

        }
        Properties props = new Properties();
        Session session = Session.getDefaultInstance(props, null);

        String msgBody = "Nume/Prenume: "+nume+" Telefon: "+telefon+" Mail: "+email+" Textul Sesizarii: "+textulses;

        Message msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress("ursu.adrian88@gmail.com", "gmail.com Adrian Ursu"));
        msg.addRecipient(Message.RecipientType.TO,
                new InternetAddress("ursu.adrian88@gmail.com", "Mr. User"));
        msg.setSubject("Mail Sesizare Campia Careiului");

        if(!att){
            msg.setText(msgBody);      
        }
        else{
            byte[] bufferTemp = new byte[size];
            for(int i=0;i<size;i++)
                bufferTemp[i]=buffer[i];

            Multipart mp=new MimeMultipart();

            MimeBodyPart textPart = new MimeBodyPart();
            textPart.setContent(msgBody, "text/plain");

            mp.addBodyPart(textPart);

            MimeBodyPart attachment= new MimeBodyPart();
            DataSource src = new ByteArrayDataSource 
                    (bufferTemp, "image/jpeg"); 
            attachment.setFileName(attname);    
            attachment.setDataHandler(new DataHandler 
                    (src));
            mp.addBodyPart(attachment);
            msg.setContent(mp);
            msg.saveChanges();



        }
        Transport.send(msg);

        resp.sendRedirect("/contact.html");
    } catch (Exception ex) {
        try {
            throw new ServletException(ex);
        } catch (ServletException e) {

            e.printStackTrace();
        }
    }

}
}
4

2 回答 2

2

我认为示例 #1 中的问题可能是您正在设置文本正文,然后尝试添加多部分。那是不正确的。消息可以是Content-Type: text/plainContent-Type: multipart/mixed但不能两者兼而有之。如果有附件,则需要将文本正文添加为多部分之一。像这样的东西(未经测试):

   if (!att) {
         msg.setText(msgBody);
   } else {

         //first build and add the text part
         MimeBodyPart textPart = new MimeBodyPart();
         textPart.setContent(msgBody, "text/plain");

         Multipart mp=new MimeMultipart();
         mp.addBodyPart(textPart));

         //now read/buffer the image data (?)
         byte[] bufferTemp = new byte[size];
         for(int i=0;i<=size;i++)
             bufferTemp[i]=buffer[i];
             // YOU NEED TO FIX THIS!!
         }

         // now add the attachment part.
         // the attachment data must be added all together, not in pieces
         MimeBodyPart attachment= new MimeBodyPart();

         // YOU NEED TO FIX THIS!!
         attachment.setFileName(attname);
         attachment.setContent(bufferTemp,"image/jpeg"); 
         mp.addBodyPart(attachment);
         msg.setContent(mp);

您读取图像数据的方式也存在问题,但您没有提供足够的代码让我告诉您如何纠正它。在将其添加到正文部分内容之前,您需要将整个图像数据读入某个对象(数组、缓冲区等)。而且您不能将其添加src为内容attachment-您必须使用实际数据-字符串或字节[]等。

为了帮助理解身体部位的概念,请尝试将消息的结构可视化。电子邮件标头列出了 的标头Content-type: multipart/mixed,其中包含Content-type: text/plain和的部分Content-type: image/jpeg

To: testuser@test.com
From: testuser2@test.com
Date: Aug 19, 2011
Content-Type: multipart/mixed; boundary="aswevb323f23f3f"

This is a message with multiple parts in MIME format.
--aswevb323f23f3f
Content-Type: text/plain

This is the body of the message.
--aswevb323f23f3f
Content-Type: image/jpeg
Content-Transfer-Encoding: base64

ZQs0bWw+CiAgPGhlYWQ+CiAgP49oZWFkPgogIDxib2R5PgogICAgPHA+VGhpcyBpcyB0aGUg
Ym9keSBvZiB0aGUgbWVzc2FnZa48L3A+CiAgPC9ib2R5Pgo8L2h0bWw+Cg==
--aswevb323f23f3f
于 2011-08-19T15:41:11.767 回答
1

我终于让它工作了。(当然)上传图片的问题。我正在覆盖缓冲区中的相同字节,我没有考虑偏移量。正确的方法是:

        int len=0;
        size=0;
        while ((len = stream.read(buffer, size,buffer.length)) != -1)
                {
                    size+=len;
                }
于 2011-08-19T18:05:44.267 回答