当前位置: 代码迷 >> Web前端 >> 文件下传回写必须设置Content-type
  详细解决方案

文件下传回写必须设置Content-type

热度:180   发布时间:2012-08-28 12:37:01.0
文件上传回写必须设置Content-type

今天解决一个文件上传的问题,代码如下:

?

@RequestMapping(value = "/upload", method = RequestMethod.POST)
    public String doUpload(Role role, @RequestParam("file") MultipartFile file, HttpServletResponse resp) {
        if (!file.isEmpty()) {
            try {
                InputStream in = file.getInputStream();
                int temp;
                while ((temp = in.read()) != -1) {
                    System.out.write(temp);
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
	resp.setContentType("text/html; charset=UTF-8");
        JSONObject json = new JSONObject();
        json.put("result", "upload ok");
        try {
            resp.getWriter().println("<textarea>" + json.toString() + "</textarea>");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

?注意上面红色的部分“resp.setContentType("text/html; charset=UTF-8");”,之前一直没有注意没有设置返回内容的格式,导致除了IE浏览器之外其他浏览器上传回写全部报错。调试了大半天,真是浪费时间,特此分享一下也算是告诫自己。

  相关解决方案