Tomcat questions about the project folder to add a new file in a web folder encounter (idea)

Download today to learn when new img in a web folder, which added several image files
Here Insert Picture Description
and then write the page, write code. . .

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<a href="/test_01_war_exploded/img/white.jpeg">图片资源</a><hr/>
<!--/test_01_war_exploded为虚拟路径-->
<a href="/test_01_war_exploded/demo3?filename=white.jpeg">图片资源</a>
</body>
</html>
package com.company;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;

@WebServlet("/demo3")
public class servletContext_03 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        /*文件下载*/
        /* 设置header content-disposition:attachment;filename=xxx */
        /*获取文件名称*/
        String filename = req.getParameter("filename");
        /*字节流加载文件进内存*/
        ServletContext con1 = this.getServletContext();
        String path = con1.getRealPath("/img/"+filename);
        //System.out.println("```filename="+filename);
        //System.out.println(path);

        /*设置response响应头*/
        String mime =con1.getMimeType(filename);
        //System.out.println(mime);
        resp.setContentType(mime);
        /*设置响应头打开方式*/
        resp.setHeader("content-disposition","attachment;filename="+filename);
        /*输入流写入输出流*/
        FileInputStream in = new FileInputStream(path);
        ServletOutputStream out = resp.getOutputStream();
        byte[] buff= new byte[1024*8];
        int len=0;
        while((len = in.read(buff))!=-1){
            out.write(buff,0,len);
        }
        in.close();
    }
}

Then run error found page 404, two hyperlinks can not be used.
The reason is that the file is actually processed idea out the folder, the compiler will generate out folders,
which placed .class files and configuration files, although img file is created in the web folder, but out of the file is not updated, still looking not see the picture

Here Insert Picture Description
solution img folder to put out a copy of the corresponding position on it. web folder that corresponds to the virtual directory / test_01_war_exploded, so directly to the img will be placed in this folder.

Published 23 original articles · won praise 4 · Views 781

Guess you like

Origin blog.csdn.net/qq_43656529/article/details/104108652