1、前端页面

<div class="tkDiv" id="addLOGO" style="display:none;z-index:12;width:800px;height:auto;margin-left:-400px;margin-top: -160px">

	  		<div class="tk1_header" style="width:800px;height:40px;line-height:40px;background: #263552 !important;color: #ffffff !important;margin-left:-10px;margin-top:-10px;">
<span style="font-size: 16px;margin-left:20px;color:#FFF" id="gn_title">添加主页图片</span>
<a id="close_modal" style="width:30px;height:20px;background-size:20px;float: right;">×</a>
</div> <div class="tk1" id="addZ" style="width:750px;height:200px;">
<div class="tk1_content" id="registerDiv" style="width:750px;">
<form id="imageForm" class="bs-docs-example form-horizontal" method="post" action="<%=path %>/webCenter.do" enctype="multipart/form-data">
<input type="hidden" name="method" value="saveConferencesImage">
<input type="hidden" id="imageId" name="imageId" value="-1">
<table style="width:750px">
<tr height="50px">
<td align="right" width="150px" >
图片名称
</td>
<td>
<input id="imageName" class="form-control" name="imageName" type="text" style="margin-left:40px;display:inline-block;height:34px;"/>
</td>
</tr>
<tr height="50px">
<td align="right" width="150px" >
上传图片
</td>
<td>
<input id="imageFile" name="imageFile" type="file" style="margin-left:40px;display:inline-block;height:34px;"/>
</td>
</tr>
</table>
</form>
</div>
<div style="border-top: 1px solid rgba(0, 0, 0, 0.1);text-align: center;">
<input id="saveBtn" type="button" class="button" value="添 加" style="border-radius:0;width:260px;height:40px;margin:auto 50px;margin:20px; background: #263552 !important;color: #ffffff !important;"/>
</div>
</div>

  2、js代码

$(function(){
$("#saveBtn").click(function(){
var imageName = $("#imageName").val();
var imageFile = $("#imageFile").val();
if(imageName == '' || imageName.length == 0){
alert("请输入图片名称");
return;
}if(imageFile == '' || imageFile.length == 0){
alert("请选择要上传的图片");
return;
}
var formData = new FormData();
formData.append("imagePath", $("#imageFile")[0].files[0]);
$.ajax({
url:"<%=path%>/webCenter.do?uploadConImage",
type:"post",
data:formData,
dataType:"json",
// 告诉jQuery不要去处理发送的数据
processData: false,
// 告诉jQuery不要去设置Content-Type请求头
contentType: false,
beforeSend: function () {
console.log("正在进行,请稍候");
},
success:function(data){
if(data.state == 0){
alert(data.msg)
}else{
$("#imageForm").submit();
}
}
})
})
})

  3、后台数据处理

  ① 第一步验证图片大小

//判断图片大小,不是这个大小的提示不能上传
@RequestMapping(params = "uploadConImage",method = RequestMethod.POST)
public void uploadConImage(HttpServletRequest request,HttpServletResponse response){
try{
MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;
MultipartFile mFile = mRequest.getFile("imagePath");
InputStream is = mFile.getInputStream();//输入流
BufferedImage bufferedImg = ImageIO.read(is);
int width = bufferedImg.getWidth();//获取图片宽高
int height = bufferedImg.getHeight();
JSONObject json = new JSONObject(); if(width != 500 && height != 300){
float bili = (float)(new Float(height)/new Float(width));
float b = (float)(Math.round(bili*100))/100;
if(b != new Float(0.45)){
json.accumulate("state", 0);
json.accumulate("msg", "请上传分辨率为500*300的图片或者长宽比为0.6的图片(高除以宽为0.6)");
}else{
json.accumulate("state", 1);
}
}else{
json.accumulate("state", 1);
}
writeJson(response, json.toString());
} catch (Exception e) {
e.printStackTrace();
}
}

  ② 在js里面用$("#imageForm").submit();提交form表单,上传图片。注意:用form表单上传图片时,在from表单上要添加  enctype="multipart/form-data"  属性。form表单看上面代码,下面是后台数据处理。

@RequestMapping(params = "method=saveConferencesImage",method = RequestMethod.POST)
public void saveConferencesImage(int imageId,String imageName,HttpServletRequest request,HttpServletResponse response){
try {
HttpSession session = this.getSession(request);
Adminuser adminUser = session.getAttribute("centerAdminUser") == null?null:(Adminuser) session.getAttribute("centerAdminUser");
if(adminUser == null){
try {
response.sendRedirect(request.getContextPath()+"/center/index.jsp");
} catch (Exception e) {
e.printStackTrace();
}
}else{
String conId = request.getSession().getAttribute("conId") == null ? null: request.getSession().getAttribute("conId").toString();
if (conId == null) {
response.sendRedirect(request.getContextPath()+"/center/index.jsp");
}
Conferences conferences = webService.getConferencesById(Integer.parseInt(conId));
ConferencesImage conferencesImage = null;
if(imageId == -1){
conferencesImage = new ConferencesImage();
}else{
conferencesImage = webService.getConferencesImageById(imageId);
}
conferencesImage.setConferencesId(Integer.parseInt(conId));
conferencesImage.setImageName(imageName);
int level = webService.getConferencesImageLevel(Integer.parseInt(conId));
conferencesImage.setLevel(level);
MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest)request;
MultipartFile mFile = mRequest.getFile("imageFile");
String fileName= mFile.getOriginalFilename();//获取文件名
fileName = fileName.substring(fileName.lastIndexOf("."),fileName.length());
String newFileName = String.valueOf(System.currentTimeMillis())+"_mainPage"+fileName;
String filePath = request.getSession().getServletContext().getRealPath("/");
filePath = filePath + conferences.getAbbreviation()+"/images/mainPage/";
File file = new File(filePath);
if(!file.exists()){
file.mkdirs();
}
File saveFile = new File(filePath+newFileName);
mFile.transferTo(saveFile);
conferencesImage.setImageUrl("/"+conferences.getAbbreviation()+"/images/mainPage/"+newFileName);
webService.saveObject(conferencesImage);
response.sendRedirect(request.getContextPath()+"/webCenter.do?getConferencesImage");
}
} catch (Exception e) {
e.printStackTrace();
}
}

  

form表单图片上传的更多相关文章

  1. JS form表单图片上传

    // 点击file 类型的input 触发的方法 function changesProvider(){ // fileProvider -> input中的name属性值 var f = do ...

  2. MVC下form表单一次上传多种类型的图片(每种类型的图片可以上传多张)

    form表单一次上传多种类型的图片(每种类型的图片可以上传多张) controller中的action方法 public ActionResult UploadImage( )        { in ...

  3. Django---CBV和FBV的使用,CBV的流程,给视图加装饰器,Request对象方法,属性和Response对象,form表单的上传

    Django---CBV和FBV的使用,CBV的流程,给视图加装饰器,Request请求对象方法,属性和Response响应对象,form表单的上传 一丶CBV和FBV       在Django中存 ...

  4. Ajax(form表单文件上传、请求头之contentType、Ajax传递json数据、Ajax文件上传)

    form表单文件上传 上菜 file_put.html <form action="" method="post" enctype="multi ...

  5. JAVA入门[16]-form表单,上传文件

    一.如何传递参数 使用 @RequestParam 可以传递查询参数.例如:http://localhost:8092/category/detail?id=1 @RequestMapping(&qu ...

  6. form表单文件上传 servlet文件接收

    需要导入jar包 commons-fileupload-1.3.2.jar commons-io-2.5.jar Upload.Jsp代码 <%@ page language="jav ...

  7. form表单文件上传提交且接口回调显示提交成功

    前端: <form method="post" enctype="multipart/form-data" id="formSubmit&quo ...

  8. Ajax serialize()提交form表单不能上传file类型

    前台form表单的提交方式有很多种,例如: 1. form表单submit直接提交的方法 2. Ajax提交的方法 3. jquery提交的方法 4. 原生js提交的方法 每一种方法都有它的优势和不足 ...

  9. SSM+form表单文件上传

    这里介绍SSM如何配置上传文件 配置springmvc.xml: <!--配置上传下载--> <bean id="multipartResolver" class ...

随机推荐

  1. io复用select方法编写的服务器

    摘要:io多路复用是通过一种机制,可以监视多个描述符,一旦某个描述符就绪(一般都是读就绪或者写就绪),就能通知应用程序进行相应的读写操作.select函数作为io多路复用的机制,第一个参数nfds是f ...

  2. 简单的ALV示例

    在这里也推荐一条链接,很适合初学者:https://blog.csdn.net/Kang_xiong/article/details/64922576 这是一个特别基础的示例,适合没有任何ABAP基础 ...

  3. IDEA新建项目时,没有Spring Initializr选项

    换了台新电脑,然后重新安装了Intellij IDEA,创建spring boot项目的时候找不到Spring Initializr选项了. 然后百度了下,发现有前辈做出了回答,就复制存到了自己随笔里 ...

  4. 小程序 web-view 嵌套的网页跳转到小程序内部页面 实现无缝连接

    需要在H5页面被作出判断和处理  点击事件发生时跳转到小程序内部页面 1.引入小程序提供的JS <script type="text/javascript" src=&quo ...

  5. Introduction to Unity UI

    https://www.raywenderlich.com/795-introduction-to-unity-ui-part-1 https://www.raywenderlich.com/794- ...

  6. Jsoup获取全国地区数据(省市县镇村)

    最近手头在做一些东西,需要一个全国各地的地域数据,从省市区到县镇乡街道的.各种度娘,各种谷歌,都没找到一个完整的数据.最后功夫不负有心人,总算找到一份相对来说比较完整的数据,但是这里的数据也只是精确到 ...

  7. input()和print()函数同时输入输出多个数据--python3

    使用input()和print()函数同时输入输出多个数据,需要空格分割输入信息 #!/usr/bin/python3#-*- conding:utf-8 -*- name, age, QQ = in ...

  8. python2入门(3)

    六.python列表(List) python最常见的序列类型python列表List使用[]表示,元素之间以逗号分隔,元素类型不需要相同 内置操作: list = [1,2,3,'four'] li ...

  9. axis2设置soap1.1或soap1.2协议

    现在Axis.Axis2都是同时支持SOAP1.1和SOAP1.2的.即在服务器端发布一个WebService服务之后,客户端既可以通过SOAP1.1版本来访问服务器的服务,也可以通过SOAP1.2版 ...

  10. Oracle误删除数据和表的恢复办法包括truncate

    在工作中我们操作数据库的时候经常会发生一个不该发生的问题:用户意外的删除一个非常重要的表或者是表中的数据而且没有备份,需要尽快的恢复,以下就是解决的办法: 主要是利用Oracle回收站的闪回特性ora ...