下面列出了怎么用javax.mail.internet.ContentDisposition的API类实例代码及写法,或者点击链接到github查看源代码。
private static String fromContentDisposition ( final String field )
{
if ( field == null || field.isEmpty () )
{
return null;
}
try
{
final ContentDisposition cd = new ContentDisposition ( field );
return cd.getParameter ( "filename" );
}
catch ( final ParseException e )
{
return null;
}
}
private static void addAttachment(BodyPart bp, EMail email)
throws UnsupportedEncodingException, MessagingException {
// Skip part without a filename
if (StringUtils.isEmpty(bp.getFileName()))
return;
// Skip part that is not an attachment
String[] values = bp.getHeader("Content-Disposition");
String disposition = "";
if (values != null && values.length > 0)
disposition = new ContentDisposition(values[0]).getDisposition();
if (!disposition.contains("attachment"))
return;
String name = MimeUtility.decodeText(bp.getFileName());
String fileName = FilenameUtils.getName(name);
EMailAttachment attachment = new EMailAttachment();
attachment.setFileName(fileName);
attachment.setMimeType(bp.getContentType());
attachment.setSize(bp.getSize());
try (InputStream is = bp.getInputStream()) {
byte[] bytes = IOUtils.toByteArray(is);
attachment.setData(bytes);
attachment.setSize(bytes.length);
} catch (IOException e) {
log.error(e.getMessage(), e);
}
email.addAttachment(attachment);
}
public String extractPayloadFilename() throws ParseException {
String s = getContentDisposition();
if (s == null || s.length() < 1) {
return null;
}
// TODO: This should be a case insensitive lookup per RFC6266
String tmpFilename = null;
ContentDisposition cd = new ContentDisposition(s);
tmpFilename = cd.getParameter("filename");
if (tmpFilename == null || tmpFilename.length() < 1) {
/* Try to extract manually */
int n = s.indexOf("filename=");
if (n > -1) {
tmpFilename = s.substring(n);
tmpFilename = tmpFilename.replaceFirst("filename=", "");
int n1 = tmpFilename.indexOf(",");
if (n1 > -1) {
s = s.substring(0, n1 - 1);
}
tmpFilename = tmpFilename.replaceAll("\"", "");
s = s.trim();
} else {
/* Try just using file separator */
int pos = s.lastIndexOf(File.separator);
if (pos >= 0) {
tmpFilename = s.substring(pos + 1);
}
}
}
return tmpFilename;
}
/**
* Extract the form name from the Content-Disposition in a
* multipart/form-data request.
*/
public static String getFieldName(BodyPart part) throws MessagingException {
String[] values = part.getHeader("Content-Disposition");
String name = null;
if (values != null && values.length > 0) {
name = new ContentDisposition(values[0]).getParameter("name");
}
return (name != null) ? name : "unknown";
}