根目录97 标签,把图片上传到服务器(跟增删改查一起实现)

 首先来个简单的html页面: enctype="multipart/form-data" encoding="multipart/form-data" action="../../后台/后台方法.do"  //form表单加上这几个属性 action指向后台添加方法

 <input type="button" id="uupdatekeyword2" value="修改" onready="true" class="btns submitform"/>
<input type="button" value="取消" id="vcancel" class="btns btnCancel" style="margin-left:10px;"/>
<input type="button" onready="true" value="开始上传" class="btns submitform"/>&nbsp; //开始上传的按钮,主要是submitform方法 //上传 javascript代码 还有一些参数跟着一起存进数据库
$(".submitform").live("click",function(){
var $this = $(this);
var j = location.href;
var idd=j.substring(j.indexOf("=")+15,j.length);  //截取字符串 获得ID
$("#iiii").val(idd);  //把ID赋给隐藏域 input,后台取得id作为条件进行查询
$("#noticecontentStr").val(editor.html());   //无法获取编辑器的值,所以赋给隐藏域,后台获取隐藏域的值进行添加
$this.parents("form").find("td input[type!='button'],td select").siblings("span").remove();
$this.parents("form").find("td input[type!='button'],td select").show();
if ($this.attr("onready") == "false") {
$this.attr("onready", "true");
$this.val("保存");
return false;}
$("#noticecontentStr").val(editor.html());
$this.parents('form').ajaxSubmit({
dataType: 'json',
type: 'post',
iframe:true,
cache:false,
resetForm:false,
beforeSubmit: function() {
//获取编辑控件的值
$this.parents("form").find(".required[disabled=false]").blur();
if ($this.parents('form').find("font[class='error']").length) {
$this.parents('form').find("font[class='error']").eq(0).siblings("input,select,textarea").focus();
return false;}},success: function(data) {
$this.parents('form').find("#fileField").hide();
if(data=='-1'){
jAlert("您目前没有权限进行此操作!");
}else if(data=="-2"){
jAlert("系统异常");
}else if(data.flag=="0"){
jAlert("保存成功","系统消息",function (){
window.location.reload();
$this.parents(".dialog").dialog("close");});
ajaxNoticeList();
}else if(data.flag == "1" || data.flag == "2" || data.flag == "3"){
jAlert(data.message);}}});
}); 前台做完开始做后台咯:(先定义一些属性和类,封装起来) private File upload;//文件的
private String uploadFileName;//文件的名称
/**
* 返回结果
*/
private TheResult tr = new TheResult(); private static List<String> allowFileSuffix = new ArrayList<String>();
public UserSeriviceImpl getLos() {
return los;
}
public void setLos(UserSeriviceImpl los) {
this.los = los;
}
public TheResult getTr() {
return tr;
}
public void setTr(TheResult tr) {
this.tr = tr;
} //下面开始进入主题
//创建公告
@RequestMapping("/添加方法.do")
public void newCelue(){
TheResult result = null;
try {  //调用下面上传文件的代码,用类对象接收(result)
result = 上传文件方法(tr);// 先上传文件,如果文件上传成功再保存公告内容
if(null != result && "0".equals(result.getFlag())){ // 主标题
String title = this.getParamNotNnll("title");
//内容
String value=this.getParamNotNnll("crmNoticeManage.contentStr");
byte[] valuebyte = value.getBytes();//......很多内容 Map<String, Object> cemap = new HashMap<String, Object>();
cemap.put("id",userId);  //把ID存到map集合里 User u = los.findeuser(cemap);
String name=u.getName();//作者 根据id获得其他表的数据 ZdcjCelue zdcjCelue=new ZdcjCelue();
zdcjCelue.setTitle(title);//主标题 ....存入对象进行添加
try {
zcService.newCelue(zdcjCelue);
result.setMessage("创建成功!");
result.setFlag("0");
} catch (Exception e) {
result.setFlag("3");
e.printStackTrace();
}
}
} catch (Exception e) {
result.setFlag("3");
e.printStackTrace();
}
outJSONData(JSONUtils.beanToJson(result));
} //开始上传文件咯! /**
* 上传附件
* @return
*/
public TheResult 上传文件方法(TheResult tr) {
String cc="celue"; //图片存在服务器上的路径
String rd="rd";
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
/**页面控件的文件流**/
MultipartFile multipartFile = multipartRequest.getFile("upload"); //upload指的是前端input的name
String fileName=multipartFile.getOriginalFilename();
String folderName=cc+"/"+DateUtil.getDataStringDir();  //产生一天的日期字符串,因为图片有可能重复,防止重复
int fileSize=0;
String stuffixForFile = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf(".") + 1);
if (!getAllowFileSuffix().contains(stuffixForFile)) {//检查文件是否在允许上传的范围之内
tr.setFlag("1");
tr.setMessage("出于安全性考虑,不允许添加此种格式(."+stuffixForFile+")文件。");
return tr;
}
try {
InputStream is=multipartFile.getInputStream();
fileSize=is.available();
if ((fileSize / 1024) > 1024 * 2) {
tr.setFlag("2");
tr.setMessage("上传文件大于2MB");
return tr;
}
String ip=GlobalUtil.pps.getProperty("FTP.ip");//上传服务器地址
String username=GlobalUtil.pps.getProperty("FTP.username");//用户名
String password=GlobalUtil.pps.getProperty("FTP.password");//密码
FTPUtil.connServer(ip, username, password,"");
FTPUtil.createDir(folderName);
FTPUtil.uploadFile(fileName, is);
} catch (IOException e) {
e.printStackTrace();
tr.setFlag("3");
tr.setMessage("上传文件异常!");
return tr;
}finally{
FTPUtil.closeServer();
}
String url="/"+folderName+"/"+fileName;
tr.setFlag("0");
tr.setMessage("上传成功!");
tr.setShowURL(url);
tr.setRecName(multipartFile.getOriginalFilename());
return tr;
}  //下面还有一个方法需要填上 public static List<String> getAllowFileSuffix() {
if (allowFileSuffix == null || allowFileSuffix.size() < 1) {
String stuffix = "gif,jpg,jpeg,png,bmp,swf,flv,swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb,doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2";
if (allowFileSuffix == null) {
allowFileSuffix = new ArrayList<String>();
}
allowFileSuffix.clear();
for (String stuf : stuffix.split(",")) {
allowFileSuffix.add(stuf);
}
}
return allowFileSuffix;
}  //不要忘记set方法 public static void setAllowFileSuffix(List<String> allowFileSuffix) {
ZdcjCelueAction.allowFileSuffix = allowFileSuffix;
}//至此 已经完成了图片上传。 显示服务器上的图片很简单<img class='img-responsive' src='http://121.41.57.4/images"+comment.coverImg+"'>一定要对应好服务器图片的位置, 上面说过有一个Result类:↓ package com.kinglo.im.util; import java.util.List; /**
* 处理结果
*
* @author tr 2012-07-17
*/
public class TheResult { /**
* 标记 0--成功,1--异常,2--失败
*/
private String flag;
/**
* 返回消息
*/
private String message; /**
* 刷新页面的访问路径
*/
private String showURL;
/**
* 是否关闭当前层(true--是,false--否)
*/
private boolean whetherClose; /**
* 是否刷新页面(true--是,false--否)
*/
private boolean whetherRefresh = true; private String checkbox; private Integer type;
private String userid;
private String subject;
private String senderName;//发送者姓名
private String reciveName;//接受者姓名
private Long sender;//发送者ID
private Long recive;//接收者ID
private String text;
private Integer taskid;
private String sendName;
private String recName;
private String tpid;
private String agentid;
private String iscomplete;
private String username;
public String getUsername() {
return username;
} public void setUsername(String username) {
this.username = username;
} private String password;
public String getPassword() {
return password;
} public void setPassword(String password) {
this.password = password;
} public String getNeibuqunid() {
return neibuqunid;
} public void setNeibuqunid(String neibuqunid) {
this.neibuqunid = neibuqunid;
} public String getWaibuqunid() {
return waibuqunid;
} public void setWaibuqunid(String waibuqunid) {
this.waibuqunid = waibuqunid;
} private String neibuqunid;
private String waibuqunid;
private String isCallerRbt;
/**
* 当前第几页
*/
private int currPage = 1;
/**
* 当前页显示记录数
*/
private int pageSize = 10; private String companyCode; private String isExtFlag;//是否转分机 private String isJobNumFlag;//是否报工号 private String isJobId;//是否弹屏 private String subaccount;
private String subaccountpwd;
private String voipid;
private String voippwd; public String getTpid() {
return tpid;
} public void setTpid(String tpid) {
this.tpid = tpid;
} public String getFlag() {
return flag;
} public void setFlag(String flag) {
this.flag = flag;
} //这里进行封装get() set()方法 } /**
* 图片上传(这个是另一种方法的action)
*/
@RequestMapping("/uploadImages.do")
public void uploadImages(){
try {
String regExp="jpg|bmp|jpeg|png|gif";
Pattern pattern=Pattern.compile(regExp,Pattern.CASE_INSENSITIVE+Pattern.MULTILINE);
System.out.println("ss:"+uploadFileName);
Matcher matcher=pattern.matcher(uploadFileName);//这个为空if(!matcher.find()){
this.outJSONDataString("{\"error\":1,\"message\":\"请上传正确格式的图片!\"}");}else{
FileInputStream fis=new FileInputStream(upload);//这个也为空
if(fis.available()>1536000){
this.outJSONDataString("{\"error\":1,\"message\":\"每张图片最大不能超过1.5MB!\"}");}else{
String width=this.getParamNotNnll("width").trim();
String height=this.getParamNotNnll("height").trim();
String title=this.getParamNotNnll("title").trim();
String align=this.getParamNotNnll("align").trim();
String url=request.getRequestURL().toString();
String path="";//getServletContext().getRealPath("").replace("\\", "\\\\")+"/noticedirectory/"+Context.getCurrentUser().getCompanyCode()+"/temp/"+DateUtil.getDateToString(new Date())+uploadFileName.substring(uploadFileName.lastIndexOf("."));
String imgPath="";//url.substring(0, url.indexOf(getRequest().getContextPath()))+getRequest().getContextPath()+"/noticedirectory/"+Context.getCurrentUser().getCompanyCode()+"/temp/"+DateUtil.getDateToString(new Date())+uploadFileName.substring(uploadFileName.lastIndexOf("."));
File file =new File(path);
if(!file.exists()){try {file.createNewFile();} catch (Exception e) {File dir=new File(file.getParent());dir.mkdirs();file.createNewFile();}}
FileOutputStream fos=new FileOutputStream(file);
int len=0;byte[] b=new byte[1024];
while((len=fis.read(b))!=-1){fos.write(b, 0, len);}fis.close();fos.flush();fos.close();
this.outStringData("{\"error\":0,\"url\":\""+imgPath+"\",\"path\":\""+path+"\",\"width\":\""+width+"\",\"height\":\""+height+"\",\"title\":\""+title+"\",\"align\":\""+align+"\"}");}}
} catch (Exception e) {e.printStackTrace();}}
上一篇:cucumber_java从入门到精通(5)使用maven创建cucumber_java项目


下一篇:JFinal极速开发实战-业务功能开发-通用表单验证器