2012-08-22 29 views
0

我用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的我無法找到一個OutputStream來的writeTo! 謝謝!

回答

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類可以完成這項工作。

然後,您只需比較讀取的字節數與文件長度就可以了。

+0

親愛的Toilal,是否有可能重寫getInputStream()來retyrn一個FilterOutputStream? – wathmal

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。