是否可以使用servlet更改上载路径?

时间:2015-02-17 16:48:18

标签: java servlets struts

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

我知道我可以使用servlet将我的上下文路径内部重定向到上下文路径之外,就像我在这附近的某个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 /“?

2 个答案:

答案 0 :(得分:0)

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

@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

答案 1 :(得分:0)

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

我试图做的是使用servlet覆盖struts操作中的上传路径,这是无法完成的,因为servlet将执行INSTEAD操作。所以不,你不能使用servlet来覆盖动作中的上传路径。