我正在尝试在同一页面中显示多种内容类型(文本/ html和图像/ png嵌入式图像)。我将图像内容和text / html内容与所有标头信息一起存储在我们的磁盘/数据库中(基本上假定我可以使用InputStream读取text / html和图像的内容)。我想创建一个同时包含text / html部分和嵌入式图像部分的HttpResponse。我遇到了一些对HttpClient / MultipartEntity的引用。所以我尝试了一个示例代码来使用MultipartEntity显示图像(保存在磁盘中),但是我在页面中看到的只是乱码。我在构建路径中引用的jar是apache-mime4j-0.6.jar,httpcore-4.0.1.jar,httpmime-4.0.jar。我正在使用apache tomacat服务器。下面是示例代码。

import java.io.*;
import java.nio.charset.Charset;

import javax.servlet.*;
import javax.servlet.http.*;

import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.InputStreamBody;


public class MyHelloWorldServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws IOException, ServletException
    {

        ServletOutputStream out = response.getOutputStream();
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE,null,Charset.forName("UTF-8"));
        //File file = new File("C:\\Users\\Public\\Pictures\\Sample Pictures\\test.msg");
        File file = new File("C:\\Users\\Public\\Pictures\\Sample Pictures\\Chrysanthemum.jpg");
        InputStream in1 = new FileInputStream(file);
        InputStreamBody fileBody1 = new InputStreamBody(new FileInputStream(file), "Chrysanthemum.jpg");
        entity.addPart("part1", fileBody1);
        entity.writeTo(out);

    }
}


还可以有人让我知道是否可以通过类似的方式添加多个内容类型并显示的部分吗?

最佳答案

也许我没有正确地对待你。似乎您想要的是创建具有相同映射的Servlet,以处理不同类型的请求?我对吗?如果这是正确的,那么为什么不根据数据库中的标头更改内容类型。

            response.setContentType("image/jpg");
            response.setContentType("text/html");


然后根据您要提供的内容来使用图像或文件:
对于html:

  response.setContentType("text/html");
  PrintWriter out = res.getWriter();
  out.println("<html>....</html>");
  out.close();


对于图像:

    ServletOutputStream stream = null;
    BufferedInputStream buf = null;
    try{

            stream = response.getOutputStream();
            File mp3 = new File("path/tofile ");

            if(request.getSession().getAttribute( "path" )!=null){
                 mp3 = new File(request.getSession().getAttribute( "path" ).toString());
                 request.getSession().setAttribute("path", null);
            }

            response.setContentType("image/jpg");
            response.setContentLength( (int) mp3.length() );

            FileInputStream input = new FileInputStream(mp3);
            buf = new BufferedInputStream(input);
            int readBytes = 0;

            while((readBytes = buf.read()) != -1)
               stream.write(readBytes);

   } catch (IOException ioe){
      throw new ServletException(ioe.getMessage());
   } finally {
       if(stream != null)
           stream.close();
       if(buf != null)
           buf.close();
   }

关于java - 显示多个内容类型httpresponse,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12793714/

10-09 00:41
查看更多