,导入js .
<script type="text/javascript"
src="${pageContext.request.contextPath}/cmsui/javascript/jquery.js"></script>
<script type="text/javascript"
src="${pageContext.request.contextPath}/cmsui/ui/jquery.form.js"></script>
HTML form 表单
<form id="imgfilesupload" action="file_imgFileUpload.action"
method="post" enctype="multipart/form-data" isclick="0">
<input type="file" name="file" dataType="Require" msg="请选择视频封面图片" />
<button id="imgsSubmit" type="button" class="button">上传</button>
</form>
JS代码
$("#imgsSubmit").click(function() {
var tf = Validator.Validate($("#imgfilesupload")[0], 2);
if (tf != true) {
return;
}
$(this).attr("disabled","disabled");
$("#imgfilesupload").ajaxSubmit({
success : function(result) {
var num = result.replace(/<[^>]+>/g, "");
var msg = "成功!";
var isclick = "1";
if (num == "0") {
msg = "失败!";
isclick = "0";
} else if (num == "-1") {
msg = "图片格式不正确!";
isclick = "0";
}
top.Dialog.alerts("提示", msg, function() {
$("#imgurl").val(num);
$("#videoimg").attr("src",num);
$("#imgfilesupload").attr("isclick", isclick);
});
}
} );
});
Action:
private File file; // 上传的文件
private String fileFileName; // 文件名称
private String fileContentType; // 文件类型
private String oldimgurl; // 上传返回结果
private String oldvideourl; // 上传返回结果
private final FileUploadServie fs = new FileUploadServie();
public void imgFileUpload() throws IOException {
boolean tf = super.checkImg(fileFileName);
if(tf==false)
super.setAjaxData("-1");
String newurl ;
if (fileFileName != null && !"".equals(fileFileName)) {
newurl = fs.fileWriteRead("Images", file, fileFileName);
if(oldimgurl!=null)
fs.removeFile(oldimgurl);
super.setAjaxData(newurl);
} else {
super.setAjaxData("-1");
}
}
调用的类:
package www.pdwy.util;
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.io.UnsupportedEncodingException;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
public class FileUploadServie {
//工程绝对路径
private final String ServerPath = ServletActionContext.getServletContext().getRealPath("");
//上传文件的绝对路径
private String FileInSerPath = null;
//上传文件的文件名字
private String fileName = null;
//存数据库使用相对定位
private String xdurl=null;
/*
* 文件上传 *
*/
public String fileWriteRead(String folders, File sfile, String imagefileName)
throws IOException {
String foldersInSerPath = ServerPath +"\\"+ folders;
// 创建File 对象
try {
File efile = null;
efile = new File(foldersInSerPath);
// 判断目录图片文件夹是否存在
if (!efile.exists()) {
// 不存在进行创建
efile.mkdirs();
}
// 获取文件后缀名
String sufName = imagefileName.substring(imagefileName
.lastIndexOf("."));
// 获取当前系统时间
String fname = "" + System.currentTimeMillis();
// 重新命名文件名字
// 判断文件是否存在
int i = 0;
do {
if (i == 0) {
fileName = fname + sufName;
} else {
fileName = fname + "(" + i + ")" + sufName;
}
FileInSerPath = foldersInSerPath +"\\"+ fileName;
xdurl =folders+"/"+fileName;
efile = new File(FileInSerPath);
i++;
} while (efile.exists() == true);
// 实例化输入输出流进行准备
InputStream is = new FileInputStream(sfile);
OutputStream os = new FileOutputStream(efile);
int temp = 0;
int len=0;
byte b[] = new byte[1024*10];
while((temp = is.read())!=-1){
b[len] = (byte) temp;
len++;
if(len==1024*10){
os.write(b, 0, len);
os.flush();
len=0;
}
}
if(temp==-1){
os.write(b, 0, len);
os.flush();
len=0;
}
// 删除缓存
sfile.delete();
is.close();
os.close();
} catch (Exception e) {
e.printStackTrace();
System.out.println("文件上传失败");
return "-1";
}
return xdurl;
}
/**
* 文件下载 type:-1 下载出错 -2:文件不存在 0:下载成功
*
* @throws UnsupportedEncodingException
*/
public int FileDown(String path, String type, String name)
throws UnsupportedEncodingException {
InputStream is = null;
OutputStream os = null;
path = ServletActionContext.getServletContext().getRealPath("") + "\\"
+ path;
// 判断文件在不在
File SerFile = new File(path);
if (!SerFile.exists())
return -2;
// 文件存在进行下步处理
// 获取后缀名
String sufName = path.substring(path.lastIndexOf("."));
// 定义文件名
String fileName = name + sufName;
// 输入流实例化
try {
is = new FileInputStream(SerFile);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return -1;
}
HttpServletResponse response = ServletActionContext.getResponse();
// 设置响应类型
response.setContentType(type);
// 输出流实例化
try {
os = response.getOutputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return -1;
}
// 设置下载文件名
response.addHeader("Content-Disposition", "attachment;filename="
+ new String(fileName.getBytes(), "iso-8859-1"));
// 设置下载文件大小
response.addHeader("Content-Length", "" + SerFile.length());
int i = 0;
byte[] b = new byte[1024 * 8];
try {
while ((i = is.read(b)) > 0) {
os.write(b, 0, i);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return -1;
}
try {
is.close();
os.flush();
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return 0;
}
// 删除文件
public boolean removeFile(String path) {
File f = null;
try{
if(path==null){
f = new File(FileInSerPath);
}else{
//转换符号
String jdPath =ServerPath+"\\"+ path.replaceAll("/","\\\\");
f = new File(jdPath);
}
// 判断文件是否存在 存在的话进行删除,否则不删除
if (f.exists()) {
f.delete();
System.out.println("删除图片");
}
}catch(Exception e){
e.printStackTrace();
return false;
}
return true;
}
}