package com.utill.tools;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import com.oemp.system.struts2.AdminAction;
@Scope("prototype")
@Controller("utill.tools.FileDownload")
public class FileDownload extends AdminAction {
public final static String MODELDIR = "uploadfiles/files/model";
/**
* 模板下载
* @author
* @return
*/
public String downloadFile() {
HttpServletResponse response =ServletActionContext.getResponse();
Map<String, String> map = getParameters();
String model=map.get("model"); //取得要下载模板的名字
System.out.println("模板名字:"+model);
//String model="tmall_trade_item.csv";
response.reset();//设置为没有缓存
response.setContentType("application/x-download;charset=GBK");
response.setHeader("Content-Disposition", "attachment;filename="+ model);//设置响应头
try {
String dir = ServletActionContext.getServletContext().getRealPath("/")+MODELDIR+"/"+model;
if(dir.indexOf("/")>-1){
dir=dir.replaceAll("/", "\\\\");
}
File downFile = new File(dir);
FileInputStream in = new FileInputStream(downFile);
OutputStream out =response.getOutputStream();
int size=in.available();
byte[] buff = new byte[size];
int read=0;
while ((read = in.read(buff, 0, buff.length)) !=-1){
out.write(buff, 0, read);
}
response.getOutputStream().flush();//flush():强制将缓冲区中的数据发送出去,不必等到缓冲区满.
response.getOutputStream().close();//关闭流
}catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
package com.utill.tools;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.LinkedHashMap;
import java.util.Map;
import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import com.oemp.system.struts2.AdminAction;
import com.oemp.util.json.JsonUtil;
import com.util.tools.UtilTools;
@Scope("prototype")
@Controller("utill.tools.FileUpload")
public class FileUpload extends AdminAction {
// 上传文件存放路径
public final static String UPLOADDIR = "uploadfiles/images";
// 上传文件1
private File file;
private String fileFileContentType;
private String fileFileName;
private String savePath;
/**
* 初始化页面
* @return
*/
public String init(){
return SUCCESS;
}
/** 上传操作 */
public String uploadFile() {
Map<String, Object> jsonBean = new LinkedHashMap<String, Object>();
ServletActionContext.getResponse().setContentType(
"text/html;charset=utf-8");
ServletActionContext.getResponse().setCharacterEncoding("utf-8");
String imgType = ".gif,.jpg,.jpeg,.png,.bmp,.swf,.csv,.xls,.xlsx,.doc,.docx,.pdf";
// 检查扩展名
String fileExt = fileFileName.substring(fileFileName.lastIndexOf(".")).toLowerCase();
if (imgType.indexOf(fileExt) < 0) {
jsonBean.put("success", "false");
jsonBean.put("message", "不允许上传此类文件!");
return super.renderJson(JsonUtil.toJsonString(jsonBean));
}
InputStream in = null;
OutputStream out = null;
try {
in = new FileInputStream(file);
String path=savePath!=null?savePath:UPLOADDIR;
String dir = ServletActionContext.getServletContext().getRealPath("/")+path;
//System.out.println("====================="+dir);
File file = new File(dir);
if (!file.exists())
file.mkdirs();
String fileName=UtilTools.getCurrentDate();
//System.err.println(fileFileName);
File uploadFile = new File(dir,fileName+fileExt);
out = new FileOutputStream(uploadFile);
byte[] buffer = new byte[1024 * 1024];
int length;
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
jsonBean.put("success", "true");
jsonBean.put("path", "/"+path+"/"+fileName+fileExt);
jsonBean.put("uploadName",fileFileName);
jsonBean.put("message", "文件上传成功!");
} catch (FileNotFoundException ex) {
jsonBean.put("success", "false");
jsonBean.put("message", "上传文件失败!");
ex.printStackTrace();
} catch (IOException ex) {
jsonBean.put("success", "false");
jsonBean.put("message", "上传文件失败!");
ex.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
return super.renderJson(JsonUtil.toJsonString(jsonBean));
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
public String getFileFileContentType() {
return fileFileContentType;
}
public void setFileFileContentType(String fileFileContentType) {
this.fileFileContentType = fileFileContentType;
}
public String getFileFileName() {
return fileFileName;
}
public void setFileFileName(String fileFileName) {
this.fileFileName = fileFileName;
}
public String getSavePath() {
return savePath;
}
public void setSavePath(String savePath) {
this.savePath = savePath;
}
}
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>ajax上传文件</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<script type="text/javascript" src="<%=path%>/js/jquery.js"></script>
<script type="text/javascript" src="<%=path%>/js/ajaxfileupload.js"></script>
</head>
<body>
上传文件:<input type="file" name="file" id="fileid">
<input id="but" type="button" value="上传">
<br/>
<br/>
<br/>
<br/>
<br/>
<form action="uploadFile.json" id="form1" name="form1" method="POST" enctype="multipart/form-data">
<input type="file" name="file" />上传文件
<input type="text" name="savePath" value="/uploadfiles/files" />
</form>
<input id="sub" type="button" value="提交form">
<script type="text/javascript">
$("#but").click(function(){
$.ajaxFileUpload({
url:"uploadFile.json",
secureuri:true,
type:"post",
fileElementId:"fileid",
data:{"savePath":"/uploadfiles/files"},
dataType:"json",
success:function(data){
alert(data.message);
},
error:function(data,status,e){
alert(data.message);
alert(e);
}
});
});
$("#sub").click(function(){
$("#form1").submit();
});
</script>
</body>
</html>