您的位置:首页 > Web前端 > JavaScript

如何解决“文件上传返回JSON数据,在IE下提示下载文件”的问题?

2017-09-06 14:56 786 查看

会返回下载提示的代码如下:

@RequestMapping("/importCar")
@ResponseBody
public ActionResult importCardInfoFromExcel(MultipartFile multExcel) throws IllegalStateException, IOException {
ActionResult result = new ActionResult();
try{

//第一次判断是否正在导入的目的是:调用导入接口的时候尚有导入操作正在进行,所以直接拒接请求
if(importing) {
result.setSuccess(false);
result.setMessage("正在导入数据,请勿重复点击!!!");
return result;//不再进行后续操作
}

synchronized (lock) {
/*第二次判断是否正在导入的目的是:之前没有任何导入操作正在进行,突然爆发多个请求
导入数据的操作, 这些并发的请求穿透了第一次判断。并在加锁的作用下串行操作,但是却没有一种机制拒绝
除了第一个导入请求之外的多余导入操作。
*/
if (importing) {
//如果正在导入,什么也不做
result.setSuccess(false);
result.setMessage("正在导入数据,请勿重复点击!!!");
return result;//不再进行后续操作
}

File excel = new File(FileUploadUtils.getUploadFileTempPath() + File.separator + SysCodeUtil.generateByUUID());
multExcel.transferTo(excel);

importing = true; //表示正在导入车辆
result = carInfoService.importCarInfo(excel, findCurrentUserId());
return result;
}

}catch (Exception e) {
result.setSuccess(false);
result.setMessage("导入数据失败");
Log.logInfo("调用导入车辆信息接口抛出异常:  ");
Log.logException(e);
return result;
}
// 放置在finally块中保证一定会被恢复原值
importing = false;
Log.logInfo("恢复导入操作标志位, importing: " + importing);

}


修复后的代码如下:

@RequestMapping("/importCar")
@ResponseBody
public void importCardInfoFromExcel(MultipartFile multExcel) throws IllegalStateException, IOException {
ActionResult result = new ActionResult();
try{

//第一次判断是否正在导入的目的是:调用导入接口的时候尚有导入操作正在进行,所以直接拒接请求
if(importing) {
result.setSuccess(false);
result.setMessage("正在导入数据,请勿重复点击!!!");
write(result);
return;//不再进行后续操作
}

synchronized (lock) {
/*第二次判断是否正在导入的目的是:之前没有任何导入操作正在进行,突然爆发多个请求
导入数据的操作, 这些并发的请求穿透了第一次判断。并在加锁的作用下串行操作,但是却没有一种机制拒绝
除了第一个导入请求之外的多余导入操作。
*/
if (importing) {
//如果正在导入,什么也不做
result.setSuccess(false);
result.setMessage("正在导入数据,请勿重复点击!!!");
write(result);
return;//不再进行后续操作
}

File excel = new File(FileUploadUtils.getUploadFileTempPath() + File.separator + SysCodeUtil.generateByUUID());
multExcel.transferTo(excel);

importing = true; //表示正在导入车辆
result = carInfoService.importCarInfo(excel, findCurrentUserId());
write(result);
}

}catch (Exception e) {
Log.logInfo("调用导入车辆信息接口抛出异常:  ");
Log.logException(e);
result.setSuccess(false);
result.setMessage("导入数据失败!");
write(result);
}
// 放置在finally块中保证一定会被恢复原值
importing = false;
Log.logInfo("恢复导入操作标志位, importing: " + importing);
}

private void write(ActionResult result) {
if (result == null) {
return;
}
PrintWriter writer = null;
try {
HttpServletResponse response = getServletResponse();
response.setContentType("text/html; charset=utf-8");
writer = response.getWriter();
writer.write(JsonUtils.object2Json(result));
writer.flush();
} catch (Exception e) {
Log.logInfo("数据写入响应流失败:  ");
Log.logException(e);
} finally {
if (writer != null) {
try {
writer.close();
} catch (Exception e) {
Log.logInfo("响应流关闭失败!:");
Log.logException(e);
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  IE json 提示下载
相关文章推荐