主要是利用FormData来实现
var formdata = new FormData(document.getElementById(“defendanttodefenceForm”));
页面数据:
<div class="DPosition">
<span>答辩演示页面</span>
</div>
<style type="text/css">
label.error
{
color:Red;
font-size:13px;
margin-left:5px;
padding-left:16px;
background:url("#springUrl('/')resources/images/unchecked.gif") left no-repeat;
}
</style>
<script>
$().ready(function () {
$("#defendanttodefenceForm").validate({
rules:{
billId: "required",
phone: "required",
defenseFile: "required"
}
})
})
</script>
<div class="mbox">
<div class="mboxR">
<!--基本信息-->
<div class="mboxRbox">
<h1 align="center">答辩演示页面</h1><br>
<form id="defendanttodefenceForm" action="#springUrl('/')defendanttodefence?save" method="post" enctype="multipart/form-data">
<div class="tabConBox_L" >
<p>
<span>订单编号:</span>
<input id="billId" name="billId" type="text" class="bor txtth" size="100" value="$!{bill.billId}"></input>
</p>
<p>
<span> </span>
<input type="button" value="查看申请人提交的仲裁申请书" class="btn_small m_r" onclick="showpdf()" style=" width: 200px;"></input>
</p>
<p>
<span>手机号码:</span>
<input id="phone" name="phone" type="text" class="bor txtth" size="100" value="$!{userInfo.phone}"></input>
</p>
<p>
<span>答辩意见书:</span>
<input id="defenseFile" name="defenseFile" type="file" class="bor txtth" size="100"></input>
</p>
</div>
<div class="btn_bottom">
<input type="button" value="提交" class="btn_small m_r" onclick="save()"></input>
<input type="reset" value="重置" class="btn_small m_r" onclick="reset()"></input>
</div>
</form>
</div>
</div>
</div>
<script type="text/javascript">
function reset() {
$(':input','#myform')
.not(':button, :submit, :reset, :hidden')
.val('')
.removeAttr('checked')
.removeAttr('selected');
}
function save() {
var formdata = new FormData(document.getElementById("defendanttodefenceForm"));
$.ajax({
type: "POST",
url: "#springUrl('/')defendanttodefence?save",
data:formdata,
processData: false, // 告诉jQuery不要去处理发送的数据
contentType: false, // 告诉jQuery不要去设置Content-Type请求头
success: function(data){
var jsondata = eval("("+data+")");
if(1==jsondata.retCod){
alert("答辩成功");
window.location.href="#springUrl('/')defendanttodefence"
}else{
alert(jsondata.msg)
}
},
error: function (data, status, e){
alert("网络错误")
}
});
}
function showpdf() {
var billId = document.getElementById("billId").value;
if(billId == '' || billId == undefined || billId == null){
alert("订单编号不能为空");
}else{
var url = "#springUrl('/')defendanttodefence/browser/"+ billId;
window.open(url, "_blank",
"top=200,left=200,height=600,width=800,status=yes," +
"toolbar=1,menubar=no,location=no,scrollbars=yes");
}
}
</script>
后台接口:
package com.itrus.laweyecloud.controller.user.test;
import com.itrus.laweyecloud.common.constant.ComNamesOfFile;
import com.itrus.laweyecloud.controller.base.AbstractController;
import com.itrus.laweyecloud.orm.entity.Bill;
import com.itrus.laweyecloud.orm.entity.FileOfBill;
import com.itrus.laweyecloud.orm.entity.SysConfig;
import com.itrus.laweyecloud.orm.entity.UserInfo;
import com.itrus.laweyecloud.pojo.FileOfBillWrap;
import com.itrus.laweyecloud.service.*;
import com.itrus.laweyecloud.utils.LocalCache;
import com.itrus.laweyecloud.utils.LogUtil;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @Author jiangwenhui
* @Description
* @Date Created in 2018/2/1 0001
*/
@Controller
@RequestMapping("/defendanttodefence")
public class DefendantToDefenceController extends AbstractController{
@Autowired
LogUtil logUtil;
@Autowired
DefendantToDefenceService defendantToDefenceService;
@Autowired
BillService billService;
@Autowired
UserInfoService userInfoService;
@Autowired
FileOfBillService fileOfBillService;
@Autowired
BillAndDefendantsService billAndDefendantsService;
@Autowired
private final static Logger logger = LoggerFactory.getLogger(DefendantToDefenceController.class);
private final static String CONTENT_DISPOSITION = "Content-Disposition";
/**
* 缓存类
*/
private LocalCache localCache = LocalCache.getInstance();
/**
* 系统设置服务
*/
@Autowired
private SysConfigService sysConfigService;
/**
* 文件存储目录标识
* trustFileDir
*/
private static final String FILE_SOURCE_KEY = "trustFileDir";
/**
* 缓存时间(12h)
*/
private static final long CACHE_TIME = 12 * 60 * 60 * 1000;
/**
* 文件存储目录
*/
private static String DEST_DIR;
/**
* 答辩演示页面
*/
@RequestMapping(produces = "text/html")
public String createForm(Model uiModel){
// uiModel.addAttribute("message")
List<Bill> billList = billService.findAll();
if(null != billList && !billList.isEmpty()){
Bill bill = billList.get(0);
uiModel.addAttribute(bill);
UserInfo userInfo = billAndDefendantsService.getPrimaryDefentdant(bill);
if(null != userInfo){
uiModel.addAttribute(userInfo);
}
}
return "defendanttodefence/create";
}
/**
* 答辩处理
*/
@RequestMapping(params = "save", method = RequestMethod.POST, produces = "text/html")
@ResponseBody
public Map<String, Object> create(
@RequestParam(value = "defenseFile", required = false) MultipartFile defenseFile,
@RequestParam(value = "billId", required = false) String billId,
@RequestParam(value = "phone", required = false) String phone){
Map<String, Object> retMap = new HashMap<String, Object>();
retMap.put("retCod", 0);
if(null == defenseFile || null == phone || null == billId){
retMap.put("msg","答辩意见书、订单编号、手机号不能为空");
return retMap;
}
Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("billId", billId);
List<Bill> billList = billService.getListByParam(paramMap);
if(null == billList || billList.isEmpty()){
retMap.put("msg","订单不存在");
return retMap;
}
Bill bill = billList.get(0);
UserInfo userInfo = userInfoService.getUserInfoByPhone(phone);
if(null == userInfo){
retMap.put("msg","用户不存在");
return retMap;
}
File file = null;
try {
// file = File.createTempFile("pdf",null);
// defenseFile.transferTo(file);
setDestDir();
file = new File(DEST_DIR + File.separator,defenseFile.getOriginalFilename());
FileUtils.copyInputStreamToFile(defenseFile.getInputStream(), file);
defendantToDefenceService.defendantToToDefence(bill, userInfo, file);
String oper = "提交答辩";
String info = "答辩对应订单id: " + bill.getBillId();
logUtil.adminlog(oper, info);
file.deleteOnExit();
retMap.put("retCod", 1);
} catch (Exception e) {
e.printStackTrace();
logger.error("class DefendantToDefenceController method create execute exception",e);
retMap.put("msg", e.getMessage());
}
return retMap;
}
@RequestMapping(value = "/browser/{billId}",method = RequestMethod.GET,produces = "text/html")
public void browserPdf(@PathVariable("billId")String billId,
HttpServletRequest request, HttpServletResponse response) {
Map<String, Object> billMap = new HashMap<String, Object>();
Map<String, Object> paramMap = new HashMap<String, Object>();
billMap.put("billId", billId);
List<Bill> billList = billService.getListByParam(billMap);
if(null == billList || billList.isEmpty()){
logger.error("defendantToDefenceController, browser " + "找不到订单");
}
Bill bill = billList.get(0);
paramMap.put("bill", bill);
paramMap.put("dataType", ComNamesOfFile.DATA_TYPE_CX_1); //程序材料
paramMap.put("fileType", ComNamesOfFile.FILE_TYPE_1); //仲裁申请书
paramMap.put("belong", ComNamesOfFile.BELONG_SQR_1); //申请人
paramMap.put("source", ComNamesOfFile.SOURCE_1); //用户上传的
try {
List<FileOfBill> fileOfBillList = fileOfBillService.getListByParam(paramMap);
if(null == fileOfBillList || fileOfBillList.isEmpty()){
logger.error("defendantToDefenceController, browser " + "找不到文件");
}
FileOfBill fileOfBill = fileOfBillList.get(0);
String path = null;
try {
//获取文件
FileOfBillWrap fileOfBillWrap = fileOfBillService.downLoadFile(fileOfBill.getBill(), fileOfBill);
File file = fileOfBillWrap.getFile();
path = file.getPath();
// 转码,防止输出到浏览器中文乱码
response.setHeader(CONTENT_DISPOSITION, "filename=" + file.getName());
response.addHeader("Content-Length", "" + file.length());
//根据文件设置文件类型
//设置头可在线浏览
response.setContentType("application/pdf");
response.setCharacterEncoding("utf-8");
OutputStream os = response.getOutputStream();
try {
IOUtils.copy(new FileInputStream(file), os);
} catch (IOException e) {
e.printStackTrace();
} finally {
if(null != os){
os.close();
}
}
} catch (Exception e) {
logger.error("defendantToDefenceController, browser " + e.getMessage());
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void setDestDir() throws Exception {
SysConfig sysConfig = (SysConfig) localCache.getCache(FILE_SOURCE_KEY);
if (null == sysConfig) {
//从数据库中获取
sysConfig = sysConfigService.selectSysConfigByType(FILE_SOURCE_KEY);
//放入缓存
localCache.setCache(FILE_SOURCE_KEY, CACHE_TIME, sysConfig);
}
DEST_DIR = sysConfig.getConfig();
}
}