RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / 问题 / 588660
Accepted
helloWorld
helloWorld
Asked:2020-11-09 06:11:49 +0000 UTC2020-11-09 06:11:49 +0000 UTC 2020-11-09 06:11:49 +0000 UTC

上传文件保存在 TomCat 哪里?

  • 772

需要将图像保存到服务器。可以吃朴实无华的图书馆吗?当我停在 oracle 教程上时。但问题是文件保存在服务器的什么位置,如何创建路径呢?

该示例使用String path = request.getParameter("MyPath");但我未在此处指定返回的null 内容还有另一个选项path = request.getServletContext().getRealPath("");返回项目的父目录。是否可以在服务器上使用此选项?

@MultipartConfig
public class FileUploadServlet extends HttpServlet {

    private final static Logger LOGGER =
            Logger.getLogger(FileUploadServlet.class.getCanonicalName());
    private static final long serialVersionUID = 7908187011456392847L;

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request,
            HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");

        // Create path components to save the file
        final String path = request.getParameter("destination");
        final Part filePart = request.getPart("file");
        final String fileName = getFileName(filePart);

        OutputStream out = null;
        InputStream filecontent = null;
        final PrintWriter writer = response.getWriter();

        try {
            out = new FileOutputStream(new File(path + File.separator
                    + fileName));
            filecontent = filePart.getInputStream();

            int read;
            final byte[] bytes = new byte[1024];

            while ((read = filecontent.read(bytes)) != -1) {
                out.write(bytes, 0, read);
            }
            writer.println("New file " + fileName + " created at " + path);
            LOGGER.log(Level.INFO, "File {0} being uploaded to {1}",
                    new Object[]{fileName, path});

        } catch (FileNotFoundException fne) {
            writer.println("You either did not specify a file to upload or are "
                    + "trying to upload a file to a protected or nonexistent "
                    + "location.");
            writer.println("<br/> ERROR: " + fne.getMessage());

            LOGGER.log(Level.SEVERE, "Problems during file upload. Error: {0}",
                    new Object[]{fne.getMessage()});
        } finally {
            if (out != null) {
                out.close();
            }
            if (filecontent != null) {
                filecontent.close();
            }
            if (writer != null) {
                writer.close();
            }
        }
    }

    private String getFileName(final Part part) {
        final String partHeader = part.getHeader("content-disposition");
        LOGGER.log(Level.INFO, "Part Header = {0}", partHeader);
        for (String content : part.getHeader("content-disposition").split(";")) {
            if (content.trim().startsWith("filename")) {
                return content.substring(
                        content.indexOf('=') + 1).trim().replace("\"", "");
            }
        }
        return null;
    }

    /**
     * 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 "Servlet that uploads files to a user-defined destination";
    }
}
servlet
  • 2 2 个回答
  • 10 Views

2 个回答

  • Voted
  1. Best Answer
    bobzer
    2020-11-10T14:47:03Z2020-11-10T14:47:03Z

    在服务器上保存文件的位置

    客户端不需要指定文件路径,而是必须在您的应用程序中配置文件存储路径。这可以通过不同的方式完成,例如,在 servlet 本身的初始化参数中:

     <servlet>
        <servlet-name>FileUploadServlet</servlet-name>
        <servlet-class>com.example.FileUploadServlet</servlet-class>
        <!-- Параметр инициализации сервлета -->
        <init-param>
            <param-name>uploadFilesPath</param-name>
            <param-value>/srv/uploads</param-value>
        </init-param>
    </servlet>
    

    在servlet中,一个参数的值可以这样获取:

    getServletContext().getInitParameter("uploadFilesPath");
    

    如何创建路径?

    File file = new File(...)
    file.getParentFile().mkdirs()
    

    调用 getParentFile() 是为了不使用文件本身的名称创建文件夹。

    可以吃朴实无华的图书馆吗?

    不需要它们,标准的 Java 语言工具就足够了:

    for (Part part : request.getParts()) {
        String fileName = URLDecoder.decode(part.getSubmittedFileName(), "UTF-8");
        String path = getServletContext().getInitParameter("uploadFilesPath");
        File file = new File(path + File.separator + fileName)
        file.getParentFile().mkdirs();
        InputStream inputStream = part.getInputStream();
        java.nio.file.Files.copy(inputStream, file.toPath());
        inputStream.close();
    }
    

    在示例中,没有检查是否存在同名文件,没有文件夹结构构建功能(一个文件夹中的许多文件可能不方便支持),没有安全控制——这些功能超出了本示例的范围问题。

    • 3
  2. Андрей
    2020-04-20T18:57:57Z2020-04-20T18:57:57Z
    getServletContext().getInitParameter("uploadFilesPath");
    Мне кажется что бы это работало нужно устанавливать параметры в 
    контекст сервлета, а не в конфиг
        <context-param>
            <param-name>uploadFilesPath</param-name>
            <param-value>/srv/uploads</param-value>
        </context-param>
    
    • 0

相关问题

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    如何停止编写糟糕的代码?

    • 3 个回答
  • Marko Smith

    onCreateView 方法重构

    • 1 个回答
  • Marko Smith

    通用还是非通用

    • 2 个回答
  • Marko Smith

    如何访问 jQuery 中的列

    • 1 个回答
  • Marko Smith

    *.tga 文件的组重命名(3620 个)

    • 1 个回答
  • Marko Smith

    内存分配列表C#

    • 1 个回答
  • Marko Smith

    常规赛适度贪婪

    • 1 个回答
  • Marko Smith

    如何制作自己的自动完成/自动更正?

    • 1 个回答
  • Marko Smith

    选择斐波那契数列

    • 2 个回答
  • Marko Smith

    所有 API 版本中的通用权限代码

    • 2 个回答
  • Martin Hope
    jfs *(星号)和 ** 双星号在 Python 中是什么意思? 2020-11-23 05:07:40 +0000 UTC
  • Martin Hope
    hwak 哪个孩子调用了父母的静态方法?还是不可能完成的任务? 2020-11-18 16:30:55 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    user207618 Codegolf——组合选择算法的实现 2020-10-23 18:46:29 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    Arch ArrayList 与 LinkedList 的区别? 2020-09-20 02:42:49 +0000 UTC
  • Martin Hope
    iluxa1810 哪个更正确使用:if () 或 try-catch? 2020-08-23 18:56:13 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5