首页 > 代码库 > [转]spring mvc 返回值类型设定
[转]spring mvc 返回值类型设定
今天遇到一个上传文件遇到的问题,在IE7和8下面会在上传完成后,弹出下载框。
查到的原因是返回值类型是json,返回头部content-type是:application/json,需要更改其返回的信息头为text/html。
还有一个问题是,返回类型是text/plain时,返回的值会被<pre></pre>标签包起来,影响前端解析。
方法一:
@RequestMapping(value = "http://www.mamicode.com/excelUploadtest", method = RequestMethod.POST)
// @ResponseBody
public void excelUploadtest(@RequestParam("file") MultipartFile file, @RequestParam("fileName") String fileName,
HttpServletResponse response) throws IOException {
response.setContentType("text/html;charset=utf-8");
response.getWriter().write("{status:1,msg:‘" + "恭喜您,上传成功!" + "‘}");
return;
}
方法二:
@RequestMapping(value = "http://www.mamicode.com/add.do")
public ResponseEntity<?> add(HttpServletRequest request) {
HttpHeaders headers = new HttpHeaders();
MediaType mediaType = new MediaType("text", "html", Charset.forName("utf-8"));
headers.setContentType(mediaType);
return new ResponseEntity<Map<String, Object>>("msg", headers, HttpStatus.OK);
}
@RequestMapping(value = "http://www.mamicode.com/excelUpload", method = RequestMethod.POST)
public ResponseEntity<JsonMessage> excelUpload(@RequestParam("file") MultipartFile file, @RequestParam("fileName") String fileName,
HttpServletResponse response) throws IOException {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.TEXT_HTML);
ResponseEntity<JsonMessage> responseEntity = new ResponseEntity<JsonMessage>(new JsonMessage("无法读取上传的Excel文件,请重试。"),headers,HttpStatus.OK);
Workbook wb = null;
if (fileName.endsWith(".xls")) {
try {
wb = new HSSFWorkbook(file.getInputStream());
} catch (Exception e) {
return responseEntity;
}
} else if (fileName.endsWith(".xlsx")) {
try {
wb = new XSSFWorkbook(file.getInputStream());
} catch (Exception e) {
return responseEntity;
}
} else {
return responseEntity;
}
// 该工具类仅仅负责解析、数据绑定(含类型转换)
// TODO 业务值判断(存在性判断,唯一性判断等)
// 返回错误画面
Integer errorCount = errorResultList.size();
if (errorCount > 0) {
JsonMessage jsonMessage = new JsonMessage();
jsonMessage.setResult(errorResultList);
jsonMessage.setErrorMsg("您有<em class=‘red‘>" + errorCount + "</em>条错误信息,上传失败!请修改模板后继续上传");
jsonMessage.setStatus(JsonMessage.STATUS_FAIL);
return new ResponseEntity<JsonMessage>(jsonMessage, headers, HttpStatus.OK);
}
List<Medicine> medicines = BeanMapper.mapList(medicineVOs, Medicine.class);
medicineService.batchInsertMedicines(medicines);
JsonMessage jsonMessage = new JsonMessage();
jsonMessage.setMsg("恭喜您,上传成功!");
jsonMessage.setStatus(JsonMessage.STATUS_SUCCESS);
return new ResponseEntity<JsonMessage>(jsonMessage, headers, HttpStatus.OK);
}
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。