附加文件上传进度

时间:2012-08-22 13:39:35

标签: java javamail

我使用javamail api从java应用程序发送带附件的电子邮件,这很简单。

File f= new File(file);
MimeBodyPart mbp2 = new MimeBodyPart();

try {
    mbp2.attachFile(f);
} catch (IOException e) {
    e.printStackTrace();
}



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

message.setContent(mp);

但我想要的是知道如何知道我的附件的上传进度,不像httpclient我找不到一个输出流到writeto! 谢谢!

2 个答案:

答案 0 :(得分:1)

请参阅方法实现。

public void attachFile(File file) throws IOException, MessagingException {
    FileDataSource fds = new FileDataSource(file);      
    this.setDataHandler(new DataHandler(fds));
    this.setFileName(fds.getName());
}

您需要使用跟踪文件上传的自定义实现覆盖FileDataSource。

您应该覆盖getInputStream()方法以返回计算读取字节数的FilterOutputStream。 Apache commons-io有CountingInputStream类可以完成这项工作。

然后,您只需将读取的字节数与文件长度进行比较即可获得进展。

答案 1 :(得分:0)

好吧,我是通过覆盖DataHandler()来实现的,而且效果非常好!

class progress extends DataHandler{
long len;
public idky(FileDataSource ds) {
    super(ds);
    len= ds.getFile().length();
    // TODO Auto-generated constructor stub
}



long transferredBytes=0;
public void writeTo(OutputStream os) throws IOException{

        InputStream instream = this.getInputStream();
        DecimalFormat dFormat = new DecimalFormat("0.00");

      byte[] tmp = new byte[4096];
      int l;
      while ((l = instream.read(tmp)) != -1)
      {
        os.write(tmp, 0, l);
        this.transferredBytes += l;
        System.out.println(dFormat.format(((double)transferredBytes/(double)this.len)*100)+"%");

      }
      os.flush();


}
}

并将其添加到MimeBodyPart。