JavaWeb displays the image in the browser

1. Background The
user uploads a picture, and after the picture is sent to the server, the user gets a link to display the picture on the browser.

2. Implementation
Suppose the project name is TestProject, and the files are placed in the uploadImages folder in the project root directory.
①The name of the picture is in English , you can open the picture directly through the link
<a href="http://localhost:8080/TestProject/uploadImages/myImage.jpg">Preview picture</a>

②The picture name contains Chinese , and the picture is uploaded through Servlet Output to the browser, use the absolute path of the image on the server
showImage.jsp
<a href="/TestProject/showImageServlet?filename=a test image.jpg">Preview image</a>

showImageServlet
public void showImage(HttpServletRequest request, HttpServletResponse response) throws Exception
{
response.setContentType("text/html; charset=UTF-8");
response.setContentType("image/jpeg");
String fname = request.getParameter("filename");
String newpath = new String(fname.getBytes("ISO-8859-1"), "UTF-8");
String absolutePath = rootPath + newpath;
FileInputStream fis = new FileInputStream(absolutePath);
OutputStream os = response.getOutputStream();
try
{
int count = 0;
byte[] buffer = new byte[1024 * 1024];
while ((count = fis.read(buffer)) != -1)
os.write(buffer, 0, count);
os.flush();
}
catch (IOException e)
{
e.printStackTrace ();
}
finally
{
if (os != null)
os.close();
if (fis != null)
fis.close();
}
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325391358&siteId=291194637