前台页面:
html:<input id="uploadToImportFile" type="file" name="file" style="width:200px;"/>
<input input type="button" value="上传" οnclick="contactAjaxFileUpload(this)"/>
JS:
<input id="uploadToImportFile" type="file" name="file" style="width:200px;"/>
<input input type="button" value="上传" οnclick="contactAjaxFileUpload(this)"/>
//验证文件类型
function isLegalFiletype(filename) {
var pattern = /(.jpg|.zip|.html|.htm)$/;
if (!pattern.exec(filename)) {
alert("文件格式不正确!");
return false;
}
return true;
}
function contactAjaxFileUpload(obj) {
if (isLegalFiletype($("#uploadToImportFile").val())) {
$.ajaxFileUpload({
url : '<%= request.getContextPath()%>/userinfo/fileupload!upload.do', //服务器地址
secureuri : false,// 一般设置为false
fileElementId : 'uploadToImportFile', // 文件上传控件的id属性 <input
dataType : 'json',
//可携带参数 data:{"type":type},
success : function(data) { // 服务器成功响应处理函数
if(data.success){
}else{
alert(data.message);
}
return;
},
error : function(data, e) {
alert("上传失败 "+e);
return;
}
});
}
}
//文件下载
function getFile(filename){
if(filename!=null&&filename!=''){
window.open(encodeURI("<%= request.getContextPath()%>/userinfo/fileupload!getFj.do?filename="+filename));
}else{
alert('文件不存在');
}
}
后台Action
public class FileUploadAction extends SimpleActionSupport{
/**
*
*/
private static final long serialVersionUID = -2542938870216611337L;
private String sp = File.separator;
private File file;
private String fileFileName;
private String fileFileContentType;
private String message = "上传失败";
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
public String getFileFileName() {
return fileFileName;
}
public void setFileFileName(String fileFileName) {
this.fileFileName = fileFileName;
}
public String getFileFileContentType() {
return fileFileContentType;
}
public void setFileFileContentType(String fileFileContentType) {
this.fileFileContentType = fileFileContentType;
}
@SuppressWarnings({ "deprecation", "resource" })
public void upload() throws Exception {
response.setContentType("text/html;charset=UTF-8");
Map<String, Object> result = new HashMap<String, Object>();
try {
File f = this.getFile();
FileInputStream fis = new FileInputStream(f);
int a = fis.available();
if(a>2097152){
message="对不起,请上传少于2M的文件!!!";
result.put("success", false);
result.put("message", message);
response.getWriter().print(JSONObject.fromObject(result));
return;
}
if(this.getFileFileName().endsWith(".exe")){
message="对不起,你上传的文件格式不允许!!!";
result.put("success", false);
result.put("message", message);
response.getWriter().print(JSONObject.fromObject(result));
return;
}
String p =sp+userinfoId+sp;
File ff = new File(path+p);
if(!ff.exists()){
ff.mkdirs();
}
String pp = p+new Date().getTime()+this.getFileFileName().substring(this.getFileFileName().lastIndexOf("."));
FileInputStream inputStream = new FileInputStream(f);
FileOutputStream outputStream = new FileOutputStream(path+pp);
byte[] buf = new byte[1024];
int length = 0;
while ((length = inputStream.read(buf)) != -1) {
outputStream.write(buf, 0, length);
}
inputStream.close();
outputStream.flush();
result.put("success", true);
result.put("id", id);
response.getWriter().print(JSONObject.fromObject(result));
} catch (Exception e) {
e.printStackTrace();
result.put("error", true);
result.put("message", message);
response.getWriter().print(JSONObject.fromObject(result));
return;
}
}
//文件下载
@SuppressWarnings("resource")
public void getFj(){
try {
String filename = request.getParameter("filename");//文件路径
File f = new File(filename);
if(f.exists()){
response.setContentLength((int)f.length());
String parameter = "filename=" + f.getName();
response.setHeader("Content-disposition", new String(parameter.getBytes("GB2312"), "ISO8859_1"));
OutputStream os = response.getOutputStream();
FileInputStream fis= new FileInputStream(f);
byte[] b = new byte[512];
int length;
while((length = fis.read(b)) > 0){
os.write(b, 0, length);
}
os.flush();
os.close();
}else{
JsonResult.err("文件不存在");
return ;
}
} catch (Exception e) {
JsonResult.err(e.getMessage());
}
}
}