JAVA实现上传:

PS:这阵子好像一直在忙,但是也没有忙什么,入职后,每天回来什么都不想做了,这个五一总结一下,具体做的有一些东西已经记不清楚了。之前写上传,找了一些资料,自己写总觉得不满意,后来在一个网站上找到一片文章,觉得很好,就借学习借鉴了。

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
 
 
public class UploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
 
//上传文件存储目录
private static final String UPLOAD_DIRECTORY = "upload";
 
// 上传设置
private static final int MEMORY_THRESHOLD  = 1024 * 1024 * 3;  // 3MB
private static final int MAX_FILE_SIZE  = 1024 * 1024 * 40; // 40MB
private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50; // 50MB
 
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
 
//检查请求是否符合上传规则
if (!ServletFileUpload.isMultipartContent(request)) {
// 不符合就停止ֹ
PrintWriter writer = response.getWriter();
writer.println("Error: Form must has enctype=multipart/form-data.");
writer.flush();
return;
}
//判定文件的大小以及文件过大时的处理
DiskFileItemFactory factory = new DiskFileItemFactory();
// 指定缓存的大小
factory.setSizeThreshold(MEMORY_THRESHOLD);
//临时文件存放位置,根据不同的操作系统而不同
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
//处理多个文件上传
ServletFileUpload upload = new ServletFileUpload(factory);
 
// 设置上传文件的最大值ֵ
upload.setFileSizeMax(MAX_FILE_SIZE);
 
 
upload.setSizeMax(MAX_REQUEST_SIZE);
 
//  构建相对于程序的存放上传文件的路径
String uploadPath = getServletContext().getRealPath("")
+ File.separator + UPLOAD_DIRECTORY;
 
//根据存储路径生成文件夹
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) {
uploadDir.mkdir();
}
 
try {
//提交请求获得上传文件的数据
//@SuppressWarnings("unchecked")
List<FileItem> formItems = upload.parseRequest(request);
 
if (formItems != null && formItems.size() > 0) {
// 遍历
for (FileItem item : formItems) {
//
if (!item.isFormField()) {
//String fileName = new File(item.getName()).getName();
//String filePath = uploadPath + File.separator + fileName;
 
String filePath = uploadPath + File.separator + "员工信息.xls";
 
File storeFile = new File(filePath);
// 写入文件
item.write(storeFile);
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
request.getRequestDispatcher("index.jsp").forward(request, response);
}
}

 

                              --好记性不如烂笔头!

 

 

 

JAVA实现的下载

PS:下载模板的Excel文件

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
public class DownloadServlet extends HttpServlet {
 
private static final long serialVersionUID = 1L;
 
protected void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
 
File serverFile = new File(
request.getSession().getServletContext().getRealPath("/") + "WEB-INF" + File.separator + "信息汇总模板.xls");
//下载后文件名叫做员工信息.xls
String fileName = java.net.URLEncoder.encode("员工信息.xls", "utf-8");
 
response.setHeader("Content-disposition", "attachment;filename="
+ fileName);
//设置为Excel的格式
response.setContentType("application/msexcel");
 
long fileLength = serverFile.length();
 
String length = String.valueOf(fileLength);
 
response.setHeader("content_Length", length);
 
OutputStream servletOutputStream = response.getOutputStream();
FileInputStream fileInputStream = new FileInputStream(serverFile);
 
byte bytes[] = new byte[1024];
int len = 0;
 
while ((len = fileInputStream.read(bytes)) != -1) {
 
servletOutputStream.write(bytes, 0, len);
}
 
servletOutputStream.close();
fileInputStream.close();
 
}
 
}

                              --好记性不如烂笔头!

 

 

简单的jxl操作Excel和邮件发送

 

PS:jxl是自己自学了jxl写的,email的功能参照了apache的邮件发送,看着有点乱。

 

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
 
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import org.apache.commons.mail.EmailAttachment;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.MultiPartEmail;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
 
public class MailSendServlet extends HttpServlet {
 
private static final long serialVersionUID = 1L;
 
Logger logger = Logger.getLogger(MailSendServlet.class);
 
@Override
public void init(ServletConfig sc) throws ServletException {
   PropertyConfigurator.configure(sc.getServletContext().getRealPath("/")
+ "WEB-INF" + File.separator + "log4j.properties");
}
 
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String path = req.getSession().getServletContext().getRealPath("/")
+ "upload" + File.separator + "员工信息.xls";
List<String> fallEmail = new ArrayList<String>();
sendEmail(fallEmail,req,resp,path);
if (fallEmail.size()>0) {
for (int i = 0; i <2; i++) {
sendEmail(fallEmail,req,resp,path);
}
}
/*邮件发送完成之后,将上传上来的文件删除*/
File delFile = new File(path);
if (delFile.exists()) {
delFile.delete();
}
req.getRequestDispatcher("sendSuccess.jsp").forward(req, resp);
 
}

 

private void sendEmail(List<String> list,HttpServletRequest req,HttpServletResponse resp,String path) throws IOException{
req.setCharacterEncoding("utf-8");
// 这个地址的作用,作为模板写入每个人的工资信息;作为邮件的附件,在写入信息后发给每个人
String wpath = req.getSession().getServletContext().getRealPath("/")
+ "WEB-INF" + File.separator + "工资条模板.xls";
Workbook book = null;
Workbook book1 = null;
WritableWorkbook wbook = null;
try {
book = Workbook.getWorkbook(new File(path));
Sheet sheet = book.getSheet(0);
int rows = sheet.getRows();
 
for (int i = 4; i < rows; i++) {
/* 获取邮箱地址*/
Cell cell1 = sheet.getCell(1, i);
String address = cell1.getContents();
/*如果在list长度大于0,且里面没有匹配这次循环出来的地址,说明这个地址的邮件已经发送成功,跳出这次循环*/
if(list.size() > 0 && (!list.contains(address))){
continue;
}
try {
book1 = Workbook.getWorkbook(new File(wpath));
wbook = Workbook.createWorkbook(new File(wpath), book1);
WritableSheet wsheet = wbook.getSheet(0);
/*
 * 一次写入一个单元格的信息,循环一次将一行的信息写入到工资条.xls里面
 */
for (int j = 0; j < 31; j++) {
Cell cell = sheet.getCell(j, i);
String content = cell.getContents();
// 第一个参数是列数,第二个参数是行,第三个参数是添加的内容
Label label = new Label(j, 4, content);
try {
wsheet.addCell(label);
} catch (WriteException e) {
e.printStackTrace();
}
}
wbook.write();
book1.close();
wbook.close();
 
sendEmail(wpath, i, address);
/*发送成功之后,将list里面发送成功的的邮箱地址删除掉*/
if(list.size() > 0 && list.contains(address)){
list.remove(address);
}
logger.info("发给"+address+"的邮件发送成功!");
}
catch (EmailException em) {
logger.error("发给"+address+"的邮件发送失败!");
list.add(address);
} catch (WriteException e) {
logger.error("发给"+address+"的邮件发送失败!");
list.add(address);
}
}
// File delFile = new File(path);
// if (delFile.exists()) {
// delFile.delete();
// }
} catch (BiffException e) {
logger.error(e.getStackTrace());
} finally {
if (book != null) {
book.close();
}
 
}
}

 

private void sendEmail(String wpath, int i, String address)
throws EmailException {
// 添加附件的设置
EmailAttachment attachment = new EmailAttachment();
attachment.setPath(wpath);
attachment.setName("本月工资条.xls");
attachment.setDescription("just a test");
attachment.setDisposition(EmailAttachment.ATTACHMENT);
// 邮件的设置
MultiPartEmail email = new MultiPartEmail();
// 腾讯企业邮箱服务器地址
email.setHostName("pop.exmail.qq.com");
email.addTo(address, "亲");
email.setAuthentication("你的企业邮箱",
"密码");
email.setSSLCheckServerIdentity(false);
email.setSubject("testaaaa" + i);
email.setFrom("你的邮箱", "对面的显示");
email.setMsg("本月工资信息");
email.attach(attachment);
email.send();
}
 
}

                              --好记性不如烂笔头