是否可以使用 servlet 更改上传路径? [英] Is it posible to change upload path with a servlet?

查看:44
本文介绍了是否可以使用 servlet 更改上传路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm gonna try to explain what I want to do here and why I need to do it this way.

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

I know I can redirect my inside of context paths to outside of context paths using a servlet like the next that I got somewhere around here, which works beautifully:

@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/"之外获取图像.

So that whenever I use the path within context "/webApp/images/mypic.jpg", it actually gets the image from my outside of context images folder "/home/mycomp/images/".

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

And it's great, because I can't modify the original code, and I only had to add this servlet to redirect it outside of context. That's why I'm trying to do the same but for uploading. I got the next piece of code to get path where the image is saved and saves it, which at the moment is within context:

    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 的结果,显然在上下文中.

(I know I' missing the part where I actually get the image, but I don't need to show that.) This saves the image in "/home/mycomp/project/webApp/images/", as that's the result of getRealPath, and it is obviously within context.

这是在 struts1 操作中完成的,这使事情变得有点复杂,因为现在我开始明白我不能从 servlet 内调用操作,或者我可以吗?

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

This leads us to the question, is it possible to save it outside of context without modifying the code that saves the images using something like the servlet, so that instead of saving it to "/home/mycomp/project/webApp/images/", it will save it to "/home/mycomp/images/"?

推荐答案

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

The answer is no, not the way I wanted to do, now that I understand better what a servlet is and how they work.

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

What I was trying to do was to overwrite the upload path in a struts action, with a servlet, which can't be done, since servlet would be executed INSTEAD of action. So no, you can't use a servlet to overwrite a upload path inside an action.

这篇关于是否可以使用 servlet 更改上传路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆