【问题标题】:Is it posible to change upload path with a servlet?是否可以使用 servlet 更改上传路径?
【发布时间】:2015-02-21 03:47:50
【问题描述】:

我将尝试解释我想在这里做什么以及为什么我需要这样做。

我知道我可以使用 servlet 将我的上下文路径内部重定向到上下文路径外部,就像我在这里某个地方得到的下一个一样,它工作得很好:

@WebServlet("/images/*")
public class ImageServlet extends HttpServlet {

// Properties ---------------------------------------------------------------------------------

private String imagePath;

// Init ---------------------------------------------------------------------------------------

public void init() throws ServletException {

    // Define base path somehow. You can define it as init-param of the servlet.
    this.imagePath = "/home/mycomp/images/";

    // In a Windows environment with the Applicationserver running on the
    // c: volume, the above path is exactly the same as "c:\var\webapp\images".
    // In Linux/Mac/UNIX, it is just straightforward "/var/webapp/images".
}

// Actions ------------------------------------------------------------------------------------

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

    // Get requested image by path info.
    String requestedImage = request.getPathInfo();

    // Check if file name is actually supplied to the request URI.
    if (requestedImage == null) {
        // Do your thing if the image is not supplied to the request URI.
        // Throw an exception, or send 404, or show default/warning image, or just ignore it.
        response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
        return;
    }

    // Decode the file name (might contain spaces and on) and prepare file object.
    File image = new File(imagePath, URLDecoder.decode(requestedImage, "UTF-8"));

    // Check if file actually exists in filesystem.
    if (!image.exists()) {
        // Do your thing if the file appears to be non-existing.
        // Throw an exception, or send 404, or show default/warning image, or just ignore it.
        response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
        return;
    }

    // Get content type by filename.
    String contentType = getServletContext().getMimeType(image.getName());

    // Check if file is actually an image (avoid download of other files by hackers!).
    // For all content types, see: http://www.w3schools.com/media/media_mimeref.asp
    if (contentType == null || !contentType.startsWith("image")) {
        // Do your thing if the file appears not being a real image.
        // Throw an exception, or send 404, or show default/warning image, or just ignore it.
        response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
        return;
    }

    // Init servlet response.
    response.reset();
    response.setContentType(contentType);
    response.setHeader("Content-Length", String.valueOf(image.length()));

    // Write image content to response.
    Files.copy(image.toPath(), response.getOutputStream());
   }
}

因此,每当我使用上下文“/webApp/images/mypic.jpg”中的路径时,它实际上会从我的上下文图像文件夹“/home/mycomp/images/”之外获取图像。

这很好,因为我不能修改原始代码,我只需要添加这个 servlet 就可以将它重定向到上下文之外。这就是为什么我试图做同样的事情,但要上传。我得到了下一段代码来获取保存图像的路径并保存它,目前在上下文中:

    String file = "imagen" + (1 + (int) (Math.random() * 100000));

    String path = httpServletRequest.getSession().getServletContext().getRealPath("/images/");

    InputStream in = imagen.getInputStream();
        OutputStream bos = new FileOutputStream(path + "/" + file);

        int byteRead = 0;
        byte[] buffer = new byte[8192];
        while ((byteRead = in.read(buffer, 0, 8192)) != -1) {
            bos.write(buffer, 0, byteRead);
        }
        bos.close();
        in.close();

(我知道我错过了实际获取图像的部分,但我不需要显示。)这会将图像保存在“/home/mycomp/project/webApp/images/”中,因为那是getRealPath 的结果,显然是在上下文中。

编辑:这是在 struts1 动作中完成的,这使事情有点复杂,因为现在我已经明白我不能从 servlet 中调用动作,或者我可以吗?强>

这引出了一个问题,是否可以在不修改使用 servlet 之类的东西保存图像的代码的情况下将其保存在上下文之外,而不是将其保存到“/home/mycomp/project/webApp/ images/”,它会保存到“/home/mycomp/images/”吗?

【问题讨论】:

    标签: java servlets struts


    【解决方案1】:

    当然,您可以更改上传目录。
    使用注解:

    @MultipartConfig(
        location="/tmp", // <-----
        fileSizeThreshold=1024*1024,    
        maxFileSize=1024*1024*5,    
        maxRequestSize=1024*1024*5*5   
    )
    

    或使用web.xml

    <multipart-config>
        <location>/tmp</location>
        <max-file-size>20848820</max-file-size>
        <max-request-size>418018841</max-request-size>
        <file-size-threshold>1048576</file-size-threshold>
    </multipart-config>
    

    参考:https://docs.oracle.com/javaee/7/tutorial/servlets011.htm

    【讨论】:

    • 嗨,dovy,这让我朝着正确的方向前进,也帮助我更好地理解了 Java,因为我是 Java 新手,只编写了大约 2 个月的 Java,我更像是一个php人。请查看我更新的问题。也许你可以帮助我更多。也许你知道我是否可以从 servlet 中调用 struts 动作?
    【解决方案2】:

    答案是否定的,不是我想要做的,现在我更好地理解了 servlet 是什么以及它们是如何工作的。

    我试图做的是用一个 servlet 覆盖 struts 操作中的上传路径,这是无法完成的,因为 servlet 将被执行而不是操作。所以不,您不能使用 servlet 覆盖操作内的上传路径。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-23
      • 2019-06-25
      • 1970-01-01
      相关资源
      最近更新 更多