step 1:前端jsp页面
广告名称: |
|
广告文件: | |
|
step 2:前端js
//step 1 选择图片触发此方法
function showPic(param){
var f = $("#"+param).val();//高端的浏览器版本现在都是无法直接拿到文件的路径的,处于保护文件考虑
var picType = f.substring(f.lastIndexOf(".")+1);
var nowTime = getNowTime();
var ficName = nowTime + "."+picType;
if(picType != "JPG" && picType != "jpg" && picType != "png" && picType != "PNG" && picType != "bmp" && picType != "BMP" && picType != "gif" && picType != "GIF"){
$.messager.alert('提示','请png/jpg/bmp/gif格式图片!');
}
var file = document.getElementById('pic').files; //获取上传的文件 是一个集合
var fileSize = file[0].size;//文件大小单位:字节
//var fileName = file[0].name;//文件名
if( fileSize >= 1024*1024*2){
$.messager.show({
title: '提示',
msg: '您上传的图片大于2M',
timeout:2000,//默认4秒关闭
showType:'slide'
});
return;
}
$("#fm").ajaxSubmit({
url:"/test/showPic.action?fileName="+ficName+"",
async:false,
type:"post",
//dataType:"json",//指定返回值类型
//data:{"fileName":ficName},
success:function(data){
if(data.res){
$("#upload_img").css("height"," 240px");
$("#upload_img").css("width"," 430px");
$("#upload_img").attr("src","/test/downLoad.action?fileName="+ficName+"");
}
}
});
return false; //最好返回false,因为如果按钮类型是submit,则表单自己又会提交一次;返回false阻止表单再次提交
}
step 3 Action层 记得set/get
private InputStream woshiStream;
private String fileName;//文件名
private File uploadFile;//图片tmp
private Map
private User user;
private Advert advert;
String path = "";
//step 1:点击上传图片将原文件复制到指定文件夹内
public String showPicture(){
path = ServletActionContext.getServletContext().getRealPath("/advert");//通过传入服务器的相对路径来拿到文件的绝对路径:父目录 绝对路径
try {
File ff = new File(path);
if(!ff.exists()){
ff.mkdirs();
}
FileUtils.copyFile(uploadFile, new File(path,fileName));
if(uploadFile.delete()){
System.out.println("临时文件删除成功");
};
} catch (IOException e) {
e.printStackTrace();
}
if(uploadFile!=null){
result.put("res", true);
}else{
result.put("res", false);
}
return "success";
}
//struts图片上传配置
result
text/html
result
text/html
//step 2:复制完成后,再将复制好的图片以流的形式展现
public String downLoadPic(){
File f = new File(path+File.separator+fileName);
try {
woshiStream = new FileInputStream(f);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return "success";
}
//struts图片预览配置
woshiStream
application/octet-stream
step 3:当你点击上传 将图片以及表单一起传过去
function upload(){
$("#fm").ajaxSubmit({
url:"/test/upload!upload.action",
async:false,
type:"post",
dataType:"json",//指定返回值类型
success:function(data){
},
error:function(){
}
})
}
struts配置
result
text/html
result
text/html
Step 4:后台处理 一般时映射到数据库,这里暂时没做
public String upload(){
System.out.println(advert.getAdName());
//在通过实体类映射到数据库
return "success";
}