前端頁面:
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==500){ alert("添加失敗"); window.location.href="./hsz_questionbase.html"; } if(obj.map.statusCode === 200){ 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="01"> 試題科目:<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="100" rows="6" 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="1" name="xsbz" checked="checked"/>顯示 <input type="radio" value="0" 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("\\")+1,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(0,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) >> 4; //拼接路徑,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(".")+1); 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(8); } /** * 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(7); } /** * 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(6); } /** * 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(4); } /** * 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(2); } }
返回結果集:
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",200); entity.map.put("message","響應成功"); return entity; } public static ResultEntity error(){ ResultEntity entity=new ResultEntity(); entity.map.put("statusCode",500); entity.map.put("message","響應失敗"); return entity; } }