java代码添加附件 java上传附件怎么做

如何将java在DOMINO中发送的邮件带上附件我们要用DOMINO5R的例子重写一下:
rti.embedObject(EmbeddedObject.EMBED_ATTACHMENT, null,
attachFilePath, attachFilePath); // 添加附件
注:其中rti = (RichTextItem) memo.createRichTextItem("Body");
让邮件带上附件就一句话java代码添加附件,很简单吧 。
如果java代码添加附件,你不明白其中的参数java代码添加附件,还是会搞不出来java代码添加附件,一个字晕java代码添加附件!
其中前两个参数我就不说了,第三个和第四个参数写成一样就可以了 。
强烈注意:
1* 添加的附件必须放在DOMINO服务器上,不能放在客户端添加附件,不要问为什么,这是事实 。你在客户端的硬盘上无论放在哪 , 它也不让你上传 。
2*我们的项目环境,DOMINO是运行在AS400上 , 它的安装目录是em_01,我们就假设把附件放在AS400 的em_01/test/test.tar,在程序使用相对路径,"test/test.tar"相对于邮件的根目录em_01.
如果,按我说的做法应该不会有问题了 。若想看一个完整例子,请参考我的“java在收 。发lotus邮件的实例了” 。
java怎么实现上传附件的功能上传附件java代码添加附件,实际上就是将文件存储到远程服务器,进行临时存储 。举例java代码添加附件:
**
* 上传文件
*
* @param fileName
* @param plainFilePath 文件路径路径
* @param filepath
* @return
* @throws Exception
*/
public static String fileUploadByFtp(String plainFilePath, String fileName, String filepath) throws Exception {
FileInputStream fis = null;
ByteArrayOutputStream bos = null;
FTPClient ftpClient = new FTPClient();
String bl = "false";
try {
fis = new FileInputStream(plainFilePath);
bos = new ByteArrayOutputStream(fis.available());
byte[] buffer = new byte[1024];
int count = 0;
while ((count = fis.read(buffer)) != -1) {
bos.write(buffer, 0, count);
}
bos.flush();
Log.info("加密上传文件开始");
Log.info("连接远程上传服务器" CCFCCBUtil.CCFCCBHOSTNAME ":" 22);
ftpClient.connect(CCFCCBUtil.CCFCCBHOSTNAME, 22);
ftpClient.login(CCFCCBUtil.CCFCCBLOGINNAME, CCFCCBUtil.CCFCCBLOGINPASSWORD);
FTPFile[] fs;
fs = ftpClient.listFiles();
for (FTPFile ff : fs) {
if (ff.getName().equals(filepath)) {
bl="true";
ftpClient.changeWorkingDirectory("/" filepath "");
}
}
Log.info("检查文件路径是否存在:/" filepath);
if("false".equals(bl)){
ViewUtil.dataSEErrorPerformedCommon( "查询文件路径不存在:" "/" filepath);
return bl;
}
ftpClient.setBufferSize(1024);
ftpClient.setControlEncoding("GBK");
// 设置文件类型(二进制)
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.storeFile(fileName, fis);
Log.info("上传文件成功:" fileName " 。文件保存路径:" "/" filepath "/");
return bl;
} catch (Exception e) {
throw e;
} finally {
if (fis != null) {
try {
fis.close();
} catch (Exception e) {
Log.info(e.getLocalizedMessage(), e);
}
}
if (bos != null) {
try {
bos.close();
} catch (Exception e) {
Log.info(e.getLocalizedMessage(), e);
}
}
}
}
备注:只需要修改上传的服务器地址、用户名、密码即可进行服务器访问上传 。根据实际需要修改即可 。
怎么用java发送带附件的邮件代码详解package email;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import sun.misc.BASE64Encoder;
public class Mail {
private static final String LINE_END = "\r\n";
private boolean isDebug = true;
private boolean isAllowReadSocketInfo = true;
private String host;
private String from;
private ListString to;
private ListString cc;
private ListString bcc;
private String subject;
private String user;
private String password;
private String contentType;
private String boundary;
private String boundaryNextPart;
private String contentTransferEncoding;
private String charset;
private String contentDisposition;
private String content;
private String simpleDatePattern;
private String defaultAttachmentContentType;
private ListMailPart partSet;
private static MapString, String contentTypeMap;
static {
// MIME Media Types
contentTypeMap = new HashMapString, String();
contentTypeMap.put("xls", "application/vnd.ms-excel");
contentTypeMap.put("xlsx", "application/vnd.ms-excel");
contentTypeMap.put("xlsm", "application/vnd.ms-excel");
contentTypeMap.put("xlsb", "application/vnd.ms-excel");
contentTypeMap.put("doc", "application/msword");
contentTypeMap.put("dot", "application/msword");
contentTypeMap.put("docx", "application/msword");
contentTypeMap.put("docm", "application/msword");
contentTypeMap.put("dotm", "application/msword");
}
private class MailPart extends Mail {
public MailPart() {
}
}
public Mail() {
defaultAttachmentContentType = "application/octet-stream";
simpleDatePattern = "yyyy-MM-dd HH:mm:ss";
boundary = "--=_NextPart_zlz_3907_"System.currentTimeMillis();
boundaryNextPart = "--"boundary;
contentTransferEncoding = "base64";
contentType = "multipart/alternative";
charset = Charset.defaultCharset().name();
partSet = new ArrayListMailPart();
to = new ArrayListString();
cc = new ArrayListString();
bcc = new ArrayListString();
}
private String getPartContentType(String fileName) {
String ret = null;
if (null != fileName) {
int flag = fileName.lastIndexOf(".");
if (0 = flagflagfileName.length() - 1) {
fileName = fileName.substring(flag1);
}
ret = contentTypeMap.get(fileName);
}
if (null == ret) {
【java代码添加附件 java上传附件怎么做】ret = defaultAttachmentContentType;
}
return ret;
}
private String toBase64(String str, String charset) {
if (null != str) {
try {
return toBase64(str.getBytes(charset));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
return "";
}
private String toBase64(byte[] bs) {
return new BASE64Encoder().encode(bs);
}
private String toBase64(String str) {
return toBase64(str, Charset.defaultCharset().name());
}
private String getAllParts() {
int partCount = partSet.size();
StringBuilder sbd = new StringBuilder(LINE_END);
for (int i = partCount - 1; i = 0; i--) {
Mail attachment = partSet.get(i);
String attachmentContent = attachment.getContent();
if (null != attachmentContent0attachmentContent.length()) {
sbd.append(getBoundaryNextPart()).append(LINE_END);
sbd.append("Content-Type: ");
sbd.append(attachment.getContentType());
sbd.append(LINE_END);
sbd.append("Content-Transfer-Encoding: ");
sbd.append(attachment.getContentTransferEncoding());
sbd.append(LINE_END);
if (i != partCount - 1) {
sbd.append("Content-Disposition: ");
sbd.append(attachment.getContentDisposition());
sbd.append(LINE_END);
}
sbd.append(LINE_END);
sbd.append(attachment.getContent());
sbd.append(LINE_END);
}
}
sbd.append(LINE_END);
sbd.append(LINE_END);
partSet.clear();
return sbd.toString();
}
private void addContent() {
if (null != content) {
MailPart part = new MailPart();
part.setContent(toBase64(content));
part.setContentType("text/plain;charset=\""charset"\"");
partSet.add(part);
}
}
private String listToMailString(ListString mailAddressList) {
StringBuilder sbd = new StringBuilder();
if (null != mailAddressList) {
int listSize = mailAddressList.size();
for (int i = 0; ilistSize; i) {
if (0 != i) {
sbd.append(";");
}
sbd.append("").append(mailAddressList.get(i)).append("");
}
}
return sbd.toString();
}
private ListString getrecipient() {
ListString list = new ArrayListString();
list.addAll(to);
list.addAll(cc);
list.addAll(bcc);
return list;
}
public void addAttachment(String filePath) {
addAttachment(filePath, null);
}
public void addTo(String mailAddress) {
this.to.add(mailAddress);
}
public void addCc(String mailAddress) {
this.cc.add(mailAddress);
}
public void addBcc(String mailAddress) {
this.bcc.add(mailAddress);
}
public void addAttachment(String filePath, String charset) {
if (null != filePathfilePath.length()0) {
File file = new File(filePath);
try {
addAttachment(file.getName(), new FileInputStream(file),
charset);
} catch (FileNotFoundException e) {
System.out.println("错误java代码添加附件:"e.getMessage());
System.exit(1);
}
}
}
java 上传附件实现方法第一,jsp上传页面内容:
%@ page contentType="text/html; charset=GBK" %
%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %
html
head
title
jsp1
/title
/head
body bgcolor="#ffffff"
html:form action="myupload.do" method="post" enctype="multipart/form-data"
html:file property="thisFile"/br
html:file property="thisFile"/br
html:submit/
/html:form
/body
/html
第二,一个javabean
package upload;
import org.apache.struts.action.ActionForm;
import org.apache.struts.upload.FormFile;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMapping;
import javax.servlet.http.HttpServletRequest;
public class FileInfo extends ActionForm {
private FormFile thisFile;
public FormFile getThisFile() {
return thisFile;
}
public void setThisFile(FormFile thisFile) {
this.thisFile = thisFile;
}
public ActionErrors validate(ActionMapping actionMapping,
HttpServletRequest httpServletRequest) {
/** @todo: finish this method, this is just the skeleton.*/
return null;
}
public void reset(ActionMapping actionMapping,
HttpServletRequest servletRequest) {
}
}
第三,一个action
package upload;
import java.io.*;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.Action;
import org.apache.struts.upload.FormFile;
public class myupload extends Action {
public ActionForward execute(ActionMapping actionMapping,
ActionForm actionForm,
HttpServletRequest request,
HttpServletResponse response) throws
FileNotFoundException, IOException {
FileInfo fileInfo = (FileInfo) actionForm;
//获取上传文件
FormFile f=fileInfo.getThisFile();
InputStream is=f.getInputStream();
//将文件存入服务器上
String filename=request.getSession().getServletContext().getRealPath("/shangchuan/" f.getFileName());
OutputStream os=new FileOutputStream(filename);
int x=0;
//优化流处理过程
byte[] buffer = new byte[8192];
while((x=is.read(buffer, 0, 8192))!=-1)
{
os.write(buffer,0,x);
}
os.close();
response.sendRedirect("jsp1.jsp");//根据实际情况跳转
return null;
}
}
java中如何实现向已有的PDF文件插入附件?可以用Spire.Pdf for Java类库给PDF文档添加附件,下面的代码是插入Excel和Word附件给你参考:
import com.spire.pdf.annotations.*;
import com.spire.pdf.attachments.PdfAttachment;
import com.spire.pdf.graphics.*;
import java.awt.*;
import java.awt.geom.Dimension2D;
import java.awt.geom.Rectangle2D;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class AttachFiles {
public static void main(String[] args) throws IOException {
//创建PdfDocument对象
PdfDocument doc = new PdfDocument();
//加载PDF文档
doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\sample.pdf");
//添加附件到PDF
PdfAttachment attachment = new PdfAttachment("C:\\Users\\Administrator\\Desktop\\使用说明书.docx");
doc.getAttachments().add(attachment);
//绘制标签
String label = "财务报表.xlsx";
PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial Unicode MS",Font.PLAIN,12),true);
double x = 35;
double y = doc.getPages().get(0).getActualSize().getHeight() - 200;
doc.getPages().get(0).getCanvas().drawString(label, font, PdfBrushes.getOrange(), x, y);
//添加注释附件到PDF
String filePath = "C:\\Users\\Administrator\\Desktop\\财务报表.xlsx";
byte[] data = https://www.04ip.com/post/toByteArray(filePath);
Dimension2D size = font.measureString(label);
Rectangle2D bound = new Rectangle2D.Float((float) (xsize.getWidth()2), (float) y, 10, 15);
PdfAttachmentAnnotation annotation = new PdfAttachmentAnnotation(bound, filePath, data);
annotation.setColor(new PdfRGBColor(new Color(0, 128, 128)));
annotation.setFlags(PdfAnnotationFlags.Default);
annotation.setIcon(PdfAttachmentIcon.Graph);
annotation.setText("点击打开财务报表.xlsx");
doc.getPages().get(0).getAnnotationsWidget().add(annotation);
//保存文档
doc.saveToFile("Attachments.pdf");
}
//读取文件到byte数组
public static byte[] toByteArray(String filePath) throws IOException {
File file = new File(filePath);
long fileSize = file.length();
if (fileSizeInteger.MAX_VALUE) {
System.out.println("file too big...");
return null;
}
FileInputStream fi = new FileInputStream(file);
byte[] buffer = new byte[(int) fileSize];
int offset = 0;
int numRead = 0;
while (offsetbuffer.length(numRead = fi.read(buffer, offset, buffer.length - offset)) = 0) {
offset= numRead;
}
if (offset != buffer.length) {
throw new IOException("Could not completely read file "
file.getName());
}
fi.close();
return buffer;
}
}
效果:
java代码添加附件的介绍就聊到这里吧,感谢你花时间阅读本站内容 , 更多关于java上传附件怎么做、java代码添加附件的信息别忘了在本站进行查找喔 。

    推荐阅读