我正在尝试使用以下代码在servlet中创建下载链接。但这不起作用。请检查或给我另一个代码或方法......
public class Downlord1 extends HttpServlet {
int BYTES_DOWNLOAD=1024;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
response.setHeader("Content-Disposition","attachment;Filename=dp.jpg");
ServletContext ctx=getServletContext();
InputStream is=ctx.getResourceAsStream("/images/krishna.jpg");
int read=0;
byte[] bytes=new byte[BYTES_DOWNLOAD];
OutputStream os=response.getOutputStream();
while((read=is.read(bytes))!=-1)
{
os.write(bytes,0, read);
}
os.flush();
os.close();
} finally {
out.close();
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
答案 0 :(得分:2)
将内容类型更改为image/jpeg
。
删除PrintWriter out = response.getWriter();
- 它未被使用,可能会导致多次调用response.getWriter
或.getOutputStream
时遇到问题。