前端页面:

  JS代码:

//选中图片
var form = document.getElementById("danxuan");
// 用表单来初始化
var formData = new FormData(form);
formData.append("multipartFile",formData.get("tplj"));
$.ajax({
url:"/testList/insertAndPicture" ,
type:"post",
data:formData,
cache: false,
processData : false, // 不处理发送的数据,因为data值是Formdata对象,不需要对数据做处理 必需写
contentType : false, // 不设置Content-type请求头 必需写
async:false,
success:function (obj){
  $("#tplj").val(""); //将输入框的值置为空字符串
   if(obj.map.statusCode==){
   alert("添加失败");
   window.location.href="./hsz_questionbase.html";
   }
   if(obj.map.statusCode === ){
   alert("添加成功");
   window.location.href="./hsz_questionbase.html";
  }
},
})

  form表单:

<form id="danxuan" action="#" method="post" enctype="multipart/form-data">
<span>请添加单选题:</span>
<br />
<input type="hidden" name="stlx" value="">
试题科目:<select id="danxuanstkm" name="stkm">
<!--后台查询出来填入-->
</select><br>
试题名称:<br /><input type="text" name="stmc" required="required" class="form-control " style="width: 300px;"/>
题干(上传图片或手动输入):
<input type="file" id="tpljdanxuan" name="tplj" multiple="multiple" >
<br />
<!--<textarea name="sttg" class="form-control" cols="" rows="" style="resize: none;width: 600px;"></textarea>-->
A选项:<input type="text" name="sttg" required="required" class="form-control" style="width: 300px;"/>
B选项:<input type="text" name="sttg" required="required" class="form-control" style="width: 300px;"/>
C选项:<input type="text" name="sttg" required="required" class="form-control" style="width: 300px;"/>
D选项:<input type="text" name="sttg" required="required" class="form-control" style="width: 300px;"/>
<br />
答案:
<input type="radio" value="A" name="stda"/>A
<input type="radio" value="B" name="stda"/>B
<input type="radio" value="C" name="stda"/>C
<input type="radio" value="D" name="stda"/>D
<br /><br />
是否显示本题:
<input type="radio" value="" name="xsbz" checked="checked"/>显示
<input type="radio" value="" name="xsbz"/>不显示 <br>
<input class="btn btn-primary" type="submit" onclick="addDX()" value="确认出题"/>
</form>

Controller层:

本来这个方法的参数写的是public ResultEntity insert(MultipartFile multipartFile,TestList testList),但是运行的时候一直报参数不匹配,所以就将前台传过来的参数全部列出来,

并在方法中添加到list集合里

//添加试题(包含图片)
@RequestMapping("/insertAndPicture")
public ResultEntity insert(MultipartFile multipartFile, String stkm, String stmc, String sttg, String stda, String xsbz, String stlx, HttpServletRequest request){
TestList testList = new TestList();
testList.setStkm(stkm);
testList.setStmc(stmc);
testList.setSttg(sttg);
testList.setStda(stda);
testList.setXsbz(xsbz);
testList.setStlx(stlx);
try{
if (multipartFile.isEmpty()){
return ResultEntity.error();
}
String stdm = getProcedure.getEightCode("nms_code_stdm_id");  //生成8位试题代码流水号//设置存到数据库的试题代码
testList.setStdm(stdm);
String sxh = getProcedure.getEightCode("nms_code_stdm_sxh"); //生成8位顺序号流水号
//设置存到数据库的顺序号
testList.setSxh(Integer.valueOf(sxh));
//设置存到数据库的出题人(获取登录用户)
HttpSession session = request.getSession();
Login info = (Login) session.getAttribute("info");
testList.setCtr(info.getUsername());
testListService.add(multipartFile,testList);
return ResultEntity.success();
}catch (Exception e){
e.printStackTrace();
return ResultEntity.error();
}
}

Service方法:

本来项目没有挂载到tomcat服务器中,所以将图片的位置存到了项目中

后来项目要发布到tomcat中,所以重新写了一个方法,将图片存到tomcat下的webapps中

package com.tphy.nursing.exam.service;

import com.tphy.nursing.exam.bean.SJXXNEXTGroup;
import com.tphy.nursing.exam.bean.TestList; import com.tphy.nursing.exam.mapper.TestListMapper;
import com.tphy.nursing.util.UploadUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile; import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List; @Service
public class TestListServiceImpl implements TestListService{
//图片上传路径
private static final String UPLOAD_DIR = url();
/*使用IDEA内置tomcat使用本方法*/
// public static String url(){
// File file = new File("src/main/webapp/upload");
// String url = file.getAbsoluteFile().toString();
// System.out.println("########图片路径########"+url);
// return url;
// }
/*挂到tomcat服务器上使用本方法*/
public static String url(){
//测试获取tomcat下的webapps路径
String upload; //存到webapps下文件的名称
String tomcat_path = System.getProperty("user.dir");
System.out.println("tomcatPath:" + tomcat_path);
//获取Tomcat服务器所在路径的最后一个文件目录
String bin_path = tomcat_path.substring(tomcat_path.lastIndexOf("\\")+,tomcat_path.length());
System.out.println(bin_path);
//若最后一个文件目录为bin目录,则服务器为手动启动
if(("bin").equals(bin_path)){//手动启动Tomcat时获取路径为:D:\Software\Tomcat-8.5\bin
//获取保存上传图片的文件路径
upload = tomcat_path.substring(,System.getProperty( "user.dir" ).lastIndexOf("\\")) +"\\webapps"+"\\upload\\";
}else{//服务中自启动Tomcat时获取路径为:D:\Software\Tomcat-8.5
upload = tomcat_path+"\\webapps"+"\\upload\\";
}
return upload;
} //不建议用new UploadUtils,因为要低耦合,建议把UploadUtils类的upload方法换成静态的方法
private UploadUtils uploadUtils = new UploadUtils();
@Autowired
private TestListMapper testListMapper; @Override
@Transactional
public void add(MultipartFile multipartFile, TestList testList) {
String newPath = uploadUtils.upload(UPLOAD_DIR, multipartFile);
System.out.println("更新后图片路径:" + newPath);
//设置存到数据库的图片路径
testList.setTplj(newPath);
//设置存到数据库的创建时间
testList.setCjsj(new Date());
//设置存到数据库的修改时间
testList.setXgsj(new Date());
testListMapper.insert(testList);
} }

工具类:

图片:

package com.tphy.nursing.util;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile; import java.io.*;
import java.util.UUID; public class UploadUtils {
public String upload(String path,MultipartFile multipartFile){
//拿到文件的原始名称,即例如a.jpg
String originalFilename = multipartFile.getOriginalFilename(); //判断是否为空
if (originalFilename==null){
return null;
}
//因为上传文件只有一个upload目录,所有的文件都会放在这个文件下,会堆积大量的文件,所以把文件进行分开在upload不同的目录中,利用hash算法就行计算分配目录。例如upload/4/5;或者upload/5/5;这种
//拿到文件原名称的hashcode
int hashCode = originalFilename.hashCode();
//拿到upload下第一个目录的名称upload/n
int dir1 = hashCode & 0xf;
//拿到upload下的n目录下的目录名称upload/n/n
int dir2 = (hashCode & 0xf0) >> ;
//拼接路径,path是传过来的文件保存路径,即upload的真实路径,
String dir = path + File.separator+dir1 + File.separator + dir2;
//把路径丢到File文件中
File file = new File(dir);
//如果d:\1\2这个文件夹不存在,才创建
if (!file.exists()){
file.mkdirs();
}
//生成新的UUID.randomUUID().toString():为了防止文件名重复
String newFileName = UUID.randomUUID().toString().replace("-","")+"."+originalFilename.substring(originalFilename.lastIndexOf(".")+);
InputStream is = null;
OutputStream os = null;
try {
is = multipartFile.getInputStream();
os = new FileOutputStream(dir+File.separator+newFileName);
//对文件进行复制
FileCopyUtils.copy(is,os);
} catch (IOException e) {
e.printStackTrace();
}finally {
if (is!=null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (os!=null){
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//返回文件的路径,以便保存到数据库中
return dir1+File.separator+dir2+File.separator+newFileName;
}
}

生成不同位数的流水号:

package com.tphy.nursing.util;

import com.tphy.nursing.system.bean.Resources;
import com.tphy.nursing.system.mapper.ResourcesMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service; import java.util.HashMap;
import java.util.Map; /**
* @author :lqw
* @date :Created in 2020/2/28 10:35
* @description:调用存储过程
* @modified By:
* @version: 1
*/
@Component
public class GetProcedure { @Autowired
ResourcesMapper resourcesMapper ; /**
* create by: lqw
* description: 获取10位自增id
* create time: 2020/3/4 17:50
*
* @param :
* @return * @return : null
*/
public String getCode(String type){ Map<String,String> params = new HashMap<>();
params.put("prm_lx",type);
resourcesMapper.GetProcedure(params);
return params.get("prm_bh");
} /**
* create by: lqw
* description: 获取两位自增id
* create time: 2020/3/4 17:51
*
* @param :
* @return * @return : null
*/
public String getTwoCode(String type){
Map<String,String> params = new HashMap<>();
params.put("prm_lx",type);
resourcesMapper.GetProcedure(params);
return params.get("prm_bh").substring(); }
/**
* create by: lqw
* description: 获取三位自增id
* create time: 2020/3/4 17:51
*
* @param :
* @return * @return : null
*/
public String getThreeCode(String type){
Map<String,String> params = new HashMap<>();
params.put("prm_lx",type);
resourcesMapper.GetProcedure(params);
return params.get("prm_bh").substring(); }
/**
* create by: lqw
* description: 获取4位自增id
* create time: 2020/3/4 17:51
*
* @param :
* @return * @return : null
*/
public String getFourCode(String type){
Map<String,String> params = new HashMap<>();
params.put("prm_lx",type);
resourcesMapper.GetProcedure(params);
return params.get("prm_bh").substring(); }
/**
* create by: lqw
* description: 获取6位自增id
* create time: 2020/3/4 17:51
*
* @param :
* @return * @return : null
*/
public String getSixCode(String type){
Map<String,String> params = new HashMap<>();
params.put("prm_lx",type);
resourcesMapper.GetProcedure(params);
return params.get("prm_bh").substring(); }
/**
* create by: lqw
* description: 获取8位自增id
* create time: 2020/3/4 17:51
*
* @param :
* @return * @return : null
*/
public String getEightCode(String type){
Map<String,String> params = new HashMap<>();
params.put("prm_lx",type);
resourcesMapper.GetProcedure(params);
return params.get("prm_bh").substring(); } }

返回结果集:

package com.tphy.nursing.util;

import java.util.HashMap;
import java.util.Map; public class ResultEntity {
public Map<String,Object> map=new HashMap<String, Object>();
public ResultEntity put(String str, Object obj){
this.map.put(str,obj);
return this;
}
public static ResultEntity success(){
ResultEntity entity=new ResultEntity();
entity.map.put("statusCode",);
entity.map.put("message","响应成功");
return entity;
}
public static ResultEntity error(){
ResultEntity entity=new ResultEntity();
entity.map.put("statusCode",);
entity.map.put("message","响应失败");
return entity;
}
}

最新文章

  1. 命名规范(数据库,c#)
  2. linux 使用fdisk分区扩容
  3. LeakCanary内存泄漏检测工具使用步骤
  4. C#方法参数传递机制
  5. nyoj 15 括号匹配(二)动态规划
  6. HttpServletRequest学习
  7. Swift开发中的一些琐碎
  8. eclipse:java.lang.OutOfMemoryError: PermGen space 最简单的解决方式
  9. &quot;is not on any development teams &quot; Xcode的账号错误问题
  10. CSS相对定位、绝对定位
  11. IT项目外包有哪些注意事项
  12. Swift - 使用下划线(_)来分隔数值中的数字
  13. var与let、const的区别
  14. django中的一对一、一对多、多对多及ForeignKey()
  15. Tarjan求强连通分量,缩点,割点
  16. spring-boot(三) HowTo
  17. Unicode编码与中文互转
  18. Jmeter接口测试——跨线程组调用参数(token为例)
  19. 页面添加友盟(CNZZ)统计和事件追踪
  20. 自定义垂直拖动的seekbar进度条

热门文章

  1. Matlib&rsquo;s lsqnonlin 和 scipy.optimize&rsquo;s least_square
  2. 用jekyll和github把网站建起来!
  3. 人心和隐私怎么防?“防出轨”APP让道德滑落
  4. C++ 走向远洋——44(项目一、点—圆—圆柱类族的设计、派生类)
  5. spring——AOP原理及源码(一)
  6. date成字符串
  7. CF 1305E. Kuroni and the Score Distribution
  8. 【echarts3】 折线图我踩过的那些坑 (tooltip 设置,line 单个点/散点不显示问题)
  9. 一文详解Hexo+Github小白建站
  10. element多层导航菜单