准备工作:
前端引入:1、jquery,我在这里用的是:jquery-1.10.2.min.js
2、ajaxfileupload.js
这里可能会报一些错,所以在json判断那里修改为(网上也有):
if ( type == "json" ){
data = r.responseText;
var start = data.indexOf(">");
if(start != -1) {
var end = data.indexOf("<", start + 1);
if(end != -1) {
data = data.substring(start + 1, end);
}
}
eval( "data = " + data );
}
末尾那里补充一段:
handleError: function( s, xhr, status, e ) {
if ( s.error ) {
s.error.call( s.context || window, xhr, status, e );
}
if ( s.global ) {
(s.context ? jQuery(s.context) : jQuery.event).trigger ( "ajaxError", [xhr, s, e] );
}
}
后台导入spring的jar包,我这里用的是:spring3.0.5
在spring.xml里配置如下:
<!-- SpringMVC上传文件时,需要配置MultipartResolver处理器 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8"/>
<!-- 指定所上传文件的总大小不能超过200KB。注意maxUploadSize属性的限制不是针对单个文件,而是所有文件的容量之和 -->
<!-- 不在这里限制了,后台各自进行限制了
<property name="maxUploadSize" value="2000000"/>
-->
</bean>
<!-- SpringMVC在超出上传文件限制时,会抛出org.springframework.web.multipart.MaxUploadSizeExceededException -->
<!-- 该异常是SpringMVC在检查上传的文件信息时抛出来的,而且此时还没有进入到Controller方法中 -->
<bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<!-- 遇到MaxUploadSizeExceededException异常时,跳转到/page/html/errorGolbal.html页面 -->
<prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">/page/html/errorGolbal.html</prop>
</props>
</property>
</bean>
这里就充分利用框架的便利性帮你都做好了,如果你不在xml里配置这些,那么在controller那里,request.getInputStream()得到的这个流不全是文件流,还包含了其他,需要你自己编码去解析,当然,要解析的话还要知道http相关报文解析知识,所以这里可以充分利用框架的便利性,有兴趣的可以研究下
好了,准备工作做好了,看下前端的具体代码:
<div id="fileUpLoad" class="manage">
添附文件
<!-- 自定义 <input type="file"/> -->
<input type="file" id="btnFile" name="btnFile" onchange="txtFoo.value=this.value;com.company.project.services.newCase.fileUpLoad()" hidden="hidden" />
<input type="text" id="txtFoo" readonly="readonly" style="width: 300px" />
<button onclick="btnFile.click()" style="height: 25px;">选择文件</button>
</div>
js代码为:
if (!window.com) {
window.com = {};
}
if (!window.com.company) {
window.com.company= {};
}
if (!window.com.company.project) {
window.com.company.project= {};
}
if (!window.com.company.project.services) {
window.com.company.project.services = {};
}
if (!window.com.company.project.services.newCase) {
window.com.company.project.services.newCase = {};
}
//生成随机guid数(参考网上)
com.company.project.services.newCase.getGuidGenerator = function() {
var S4 = function() {
return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
};
return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
};
//上传文件
com.company.project.services.newCase.fileUpLoad = function(){
var fileName = $("#btnFile").val();//文件名
fileName = fileName.split("\\");
fileName = fileName[fileName.length-1];
var guid = com.company.project.services.newCase.getGuidGenerator();//唯一标识guid
var data = {guid:guid};
jQuery.ajaxSettings.traditional = true;
$.ajaxFileUpload({
url : '/PROJECT/function.do?method=fileUpLoad',
secureuri : false,//安全协议
fileElementId:'btnFile',//id
type : 'POST',
dataType : 'json',
data:data,
async : false,
error : function(data,status,e) {
alert('Operate Failed!');
},
success : function(json) {
if (json.resultFlag==false){
alert(json.resultMessage);
}else{
alert('文件上传成功!');
var next = $("#fileUpLoad").html();
$("#fileUpLoad").html("<div id='"+guid+"'>"+"文件:"+fileName+" <a href='#' onclick='com.company.project.services.newCase.filedelete("+"\""+guid+"\""+","+"\""+fileName+"\""+")'>删除</a>"+"<br/></div>");
$("#fileUpLoad").append(next);
}
}
});
};
//文件删除
com.company.project.services.newCase.filedelete = function(guid,fileName){
jQuery.ajaxSettings.traditional = true;
var data = {guid:guid,fileName:fileName};
$.ajax({
url : '/PROJECT/function.do?method=filedelete',
type : 'POST',
dataType : 'json',
data:data,
async : false,
error : function() {
alert('Operate Failed!');
},
success : function(json) {
if (json.resultFlag==false){
alert(json.resultMessage);
}else{
alert('删除成功!');
$("#"+guid).remove();
}
}
});
};
----------------------------------------------------------------------------------
注:如果你对ajax不熟悉,或者由于浏览器等原因,致使上述方式提交出现各种问题,那么你可以用form表单形式提交,代码片段如下:
<div id="fileUpLoad" class="manage">
<form id="needHide" action="/工程/function.do?method=fileUpLoad" method="post" enctype="multipart/form-data" target = "hidden_frame">
<!-- 自定义 <input type="file"/> -->
<input type="file" id="btnFile" name="btnFile" onchange="txtFoo.value=this.value;com.company.project.services.newCase.fileUpLoad()" hidden="hidden"/>
</form>
添附文件
<input type="text" id="txtFoo" readonly="readonly" style="width: 300px" />
<button onclick="btnFile.click()" style="height: 25px;">选择文件</button>
<iframe name='hidden_frame' id="hidden_frame" style='display: none' onload="com.company.project.services.newCase.statusCheck()"></iframe>
</div>
js代码写为:
var flag = true;
com.company.project.services.newCase.statusCheck = function(){
if(flag == false){
var status = hidden_frame.window.document.getElementById("hideForm").innerHTML;
console.log(status);
}
flag = false;
};
//上传文件
com.company.project.services.newCase.fileUpLoad = function(){
$("#needHide").submit();
}
后台代码主要在最后变为:
PrintWriter printWriter = response.getWriter();
printWriter.write("<div id='hideForm'>1111</div>");
----------------------------------------------------------------------------------
后台对应java代码段为:
@RequestMapping(params = "method=fileUpLoad")
//btnFile对应页面的name属性
public void fileUpLoad(@RequestParam MultipartFile[] btnFile, HttpServletRequest request, HttpServletResponse response){
try{
//文件类型:btnFile[0].getContentType()
//文件名称:btnFile[0].getName()
if(btnFile[0].getSize()>Integer.MAX_VALUE){//文件长度
OutputUtil.jsonArrOutPut(response, JSONArray.fromObject("上传文件过大!"));
}
InputStream is = btnFile[0].getInputStream();//多文件也适用,我这里就一个文件
//String fileName = request.getParameter("fileName");
String guid = request.getParameter("guid");
byte[] b = new byte[(int)btnFile[0].getSize()];
int read = 0;
int i = 0;
while((read=is.read())!=-1){
b[i] = (byte) read;
i++;
}
is.close();
OutputStream os = new FileOutputStream(new File("D://"+guid+"."+btnFile[0].getOriginalFilename()));//文件原名,如a.txt
os.write(b);
os.flush();
os.close();
OutputUtil.jsonOutPut(response, null);
}catch (Exception e) {
OutputUtil.errorOutPut(response, "系统异常");
}
}
@RequestMapping(params = "method=filedelete")
public void filedelete(HttpServletRequest request, HttpServletResponse response){
try{
String guid = request.getParameter("guid");
String fileName = request.getParameter("fileName");
File file = new File("D://"+guid+"."+fileName);
boolean isDeleted = file.delete();
if(!isDeleted){
OutputUtil.errorOutPut(response, "文件删除失败");
}
OutputUtil.jsonArrOutPut(response, null);
}catch (Exception e) {
OutputUtil.errorOutPut(response, "系统异常");
}
}
另外:如果是图片上传的话,你也可以不保存在什么临时目录,可以用base64进行编解码,网上也有很多,简单介绍下:
后台只要这么做:
//得到byte数组后
BASE64Encoder base64e = new BASE64Encoder();
JSONArray ja = new JSONArray();
String base64Str = base64e.encode(b);
ja.add(base64Str);
OutputUtil.jsonArrOutPut(response, JSONArray.fromObject(ja));
前台页面只要这么就可以拿到了:
$("#fileUpLoad")
.append("<image src='"+"data:image/gif;base64,"+json.resultMessage[0]+"' >");
对于json相关不大了解的可以参考我的博文:
http://quarterlifeforjava.iteye.com/blog/2024336
效果和iteye的相似:
补充:如果要让表单提交后还是留在当前页面,除了Ajax还可以用iframe,代码如下:
其实关键就是iframe和form中的target
<form target="actionframe" id="needHide" action="/项目名/project.do?method=fileUpLoad" method="post" enctype="multipart/form-data">
<input type="file" id="btnFile" name="btnFile" onchange="txtFoo.value=this.value;" hidden="hidden" />
<input type="text" id="txtFoo" disabled="disabled" style="width: 420px" />
</form>
<iframe width="0" height="0" name="actionframe"></iframe>
另外关于excel的导入导出可以参考下面的博客:http://xiaoxiong-it.iteye.com/blog/1433131
简单介绍下:
前台页面:
<form id="that_excel_submit" action="/项目名/translate.do?method=excelInput" method="post">
<input id="fileName" type="file" style="font-size: 10;height: 22px;width: 120px;"/>
<input type="button" style="font-size: 15;height: 23px;width: 120px;color:#FFFFFF;background:url(../images/button1.png);border-radius:2px;border-style:none;" onclick="com.compay.project.services.translate.excelInput()" value="EXCEL文件导入"/>
</form>
<!-- -------------------------------------------------- -->
<form id="this_excel_submit" action="/项目名/translate.do?method=excelExport" method="post">
<input type="hidden" name="searchInfo" id="input_searchInfo"/>
<input type="hidden" name="type" id="input_type"/>
<input type="hidden" name="addStartDate" id="input_addStartDate"/>
<input type="hidden" name="addEndDate" id="input_addEndDate"/>
<input type="hidden" name="modStartDate" id="input_modStartDate"/>
<input type="hidden" name="modEndDate" id="input_modEndDate"/>
<input type="hidden" name="pageIndex" id="input_pageIndex"/>
<input type="radio" id="exportCheck" value="0" name="exportCheck" checked="checked"/>当前页
<input type="radio" id="exportCheck" value="1" name="exportCheck"/>所有
<input type="button" style="font-size: 15;height: 23px;width: 120px;color:#FFFFFF;background:url(../images/button1.png);border-radius:2px;border-style:none;" onclick="com.company.project.services.translate.excelExport()" value="EXCEL文件导出"/>
</form>
js那里的话就是:$("#ID").submit();
后台如下:
@Controller
@RequestMapping("/translate.do")
public class Test {
@RequestMapping(params = "method=excelExport")
@Transactional(rollbackFor = Exception.class)
public void excelExport(HttpServletRequest request, HttpServletResponse response){
try {
JSONArray ja = new JSONArray();//从数据库中查出
response.reset();
response.setContentType("application/octet-stream");
response.addHeader("Content-Disposition","attachment;filename="+URLEncoder.encode("新建文件", "UTF-8")+".xlsx");//excel文件名
OutputStream out = response.getOutputStream();//new FileOutputStream("D:"+File.separator+"a.xlsx");//文件本地存储地址
//创建一个新的excel
XSSFWorkbook wb = new XSSFWorkbook();//XSSFWorkbook
//创建sheet页
XSSFSheet sheet = wb.createSheet("术语及解释");//sheet名
//创建行数
XSSFRow[] row = new XSSFRow[ja.size()+1];
//设置第一行为头
row[0] = sheet.createRow(0);
for(int i=0;i<14;i++){
XSSFCell headerCell = row[0].createCell(i);//在第一行创建14列
headerCell.setCellValue(new XSSFRichTextString("分类"+i));//分别在14列插入数据
}
//第i行插入数据
for (int i = 1; i < row.length; i++) {//从1开始,因为第一行已经设置过了
row[i] = sheet.createRow(i);
sheet.setDefaultColumnWidth(30);//设置列的长度
@SuppressWarnings("unchecked")
Map<String,Object> m = (Map<String,Object>)(ja.get(i-1));
XSSFCell[] headerCell = new XSSFCell[15];//15列
for(int j=0;j<15;j++){
headerCell[j] = row[i].createCell(j);
headerCell[j].setCellValue(new XSSFRichTextString((String)m.get("数据库里对应字段(key值)")));
}
}
wb.write(out);
out.flush();
out.close();
} catch (Exception e) {
//异常 e.printStackTrace();
throw new RuntimeException(new String());
}
}
@RequestMapping(params = "method=excelInput")
@Transactional(rollbackFor = Exception.class)
public void excelInput(HttpServletRequest request, HttpServletResponse response){
try{
//String filePath = request.getParameter("filePath");
InputStream fis = request.getInputStream();;
//创建工作薄
HSSFWorkbook hwb = new HSSFWorkbook(new POIFSFileSystem(fis));
//得到sheet
for (int i = 0; i < hwb.getNumberOfSheets(); i++) {
System.out.println("1");
}
//XSSFSheet sheet = hwb.getSheetAt(0);
OutputUtil.jsonArrOutPut(response, null);
}catch (Exception e) {
OutputUtil.errorOutPut(response, JtmaConstants.SYSTEM_ERRCODE);//异常
throw new RuntimeException(new String());
}
}
}
关于文件上传下载建议用缓冲流来写,简单示例如下:
@RequestMapping(params = "method=fileUpLoad")
//btnFile对应页面的name属性
public void fileUpLoad(@RequestParam MultipartFile[] btnFile, HttpServletRequest request, HttpServletResponse response){
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try{
//文件类型:btnFile[0].getContentType()
//文件名称:btnFile[0].getName()
//if(btnFile[0].getSize()>Integer.MAX_VALUE){//文件长度
// OutputUtil.jsonArrOutPut(response, JSONArray.fromObject("上传文件过大!"));
//}
String fileForCaseId = request.getParameter("fileForCaseId");
InputStream is = btnFile[0].getInputStream();//多文件也适用,我这里就一个文件
String filePath = Constants.FILE_ROOT_PATH+File.separator+fileForCaseId;
File file = new File(filePath);
if(!(file.exists())){
file.mkdirs();//如果不存在该文件目录,则创建
}/**else{//关于冗余文件的删除需再作详细考虑,因为涉及到还原操作
String fileList[] = file.list();
for (int j = 0; j < fileList.length; j++) {
File delfile = new File(filePath + File.separator + fileList[j]);
delfile.delete();
}
}*/
File fullFilePath = new File(filePath+File.separator+btnFile[0].getOriginalFilename());//判断文件是否存在
long fileSize = (long)btnFile[0].getSize();
byte[] b = new byte[1024*1024*1];//缓冲区每次读1MB
if(fileSize<=b.length){//连缓冲1M都达不到
b = new byte[(int)fileSize];
}
int bLength = b.length;
if(!(fullFilePath.exists())){
bis = new BufferedInputStream(is);
bos = new BufferedOutputStream(new FileOutputStream(fullFilePath,true));
while(fileSize>0){
bis.read(b, 0, bLength);
bos.write(b, 0, bLength);
fileSize = fileSize - bLength;
}
}
//PrintWriter printWriter = response.getWriter();
//printWriter.write("<div id='hideForm'>1</div>");
OutputUtil.jsonOutPut(response, null);
}catch (Exception e) {
/**
try {
PrintWriter printWriter = response.getWriter();
printWriter.write("<div id='hideForm'>0</div>");
} catch (IOException e1) {
OutputUtil.errorOutPut(response, "系统异常");
}
*/
OutputUtil.errorOutPut(response, JtmaConstants.SYSTEM_ERRCODE);//异常
}finally{
try {
if(bos!=null){
bos.close();
}
if(bis!=null){
bis.close();
}
} catch (IOException e) {
OutputUtil.errorOutPut(response, JtmaConstants.SYSTEM_ERRCODE);//异常
}
}
}
@RequestMapping(params = "method=fileDownLoad")
@Transactional(rollbackFor = Exception.class)
public void fileDownLoad(HttpServletRequest request, HttpServletResponse response){
FileInputStream fos = null;
ServletOutputStream sos = null;
try{
String caseId = request.getParameter("caseId");
String fileName = URLDecoder.decode(request.getParameter("fileName"),"UTF-8");
response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
response.setContentType("application/octet-stream");
response.setContentType("application/OCTET-STREAM;charset=UTF-8");
byte b[] = new byte[1024*1024*1];//1M
int read = 0;
fos = new FileInputStream(new File(Constants.FILE_ROOT_PATH+File.separator+caseId+File.separator+fileName));
sos = response.getOutputStream();
while((read=fos.read(b))!=-1){
sos.write(b,0,read);//每次写1M
}
//OutputUtil.jsonOutPut(response, null);
}catch (Exception e) {
throw new RuntimeException("");
}finally{
try {
if(sos!=null){
sos.close();
}
if(fos!=null){
fos.close();
}
} catch (IOException e) {
throw new RuntimeException("");
}
}
}
关于邮件的发送,简单示例如下:
简单邮件发送:
Properties properties = new Properties();
//设置邮件服务器
properties.put("mail.smtp.host", SMTP_HOST);
//验证
properties.put("mail.smtp.auth", "false");
//根据属性新建一个邮件会话
Session mailSession = Session.getInstance(properties);
mailSession.setDebug(true);
//建立消息对象
MimeMessage mailMessage = new MimeMessage(mailSession);
//发件人
mailMessage.setFrom(new InternetAddress(fromAddress));
//收件人
mailMessage.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(toAddress));
//主题
mailMessage.setSubject(title);
//内容
mailMessage.setText(message);
//发信时间
mailMessage.setSentDate(new Date());
mailMessage.setContent(message, "text/html;charset=gb2312" );
//存储信息
//mailMessage.saveChanges();
Transport trans = mailSession.getTransport("smtp");
//发送
trans.send(mailMessage);