如何在Java中获取绝对路径

乌代·康杜鲁(Uday Konduru)

目前我正在从浏览器上传一个图像。现在后端有Java代码,我正在检索此图像并将其转换为字节数组并将其存储到数据库中,这部分工作正常

该代码如下所示:

String fromLocal = "D:/123.jpg";
        File file = new File(fromLocal);
        InputStream inputStream = null;
        byte[] bFile= null;
        byte[] imageData = null;
        try {
            inputStream = new BufferedInputStream(new FileInputStream(file));
            ByteArrayOutputStream baos = new ByteArrayOutputStream(8192);
            bFile = new byte[8192];
            int count;
            while((count = inputStream.read(bFile))> 0){
                baos.write(bFile, 0, count);
            }
            bFile = baos.toByteArray();
            if(bFile.length > 0){
                imageData = bFile;
            }
            baos.flush();
            inputStream.close();
        } catch (Exception ioe) {
            //throw ioe;
        }

问题是,每当我尝试对图像路径进行硬编码(例如此处的D:/123.jpg)时,它的工作原理都很好。现在,它取决于用户和客户端,他可以从任何驱动器和任何目录中加载映像。我没有使用servlet的特权。我的查询是:

1.现在,如果我尝试从浏览器从D:/123.jpg上传相同的图像,我只会得到123.jpg,而不是像D:/123.jpg这样的绝对路径。由于相同的原因,现在无法处理图像。

2.如何知道用户尝试上传图像的特定路径(比如说用户从C:/images/123.jpg上传图像),那么如何获得该绝对路径。

我尽力详细说明了我的问题,让我知道是否有不清楚的地方,我会尝试以其他方式进行解释。

TJ人群

如果用户正在将文件上传到servlet,则该文件包含在请求正文中,而不是在服务器上的任何路径上。最终用户的客户端计算机上的路径无关紧要(而且无论如何,您都无法访问它,甚至客户端也是如此)。

此处提供有关文件上传的Java EE 6教程:http ://docs.oracle.com/javaee/6/tutorial/doc/glraq.html

根本上(从该示例中),如果用于上载的字段的名称为file,则可以在servlet中执行此操作:

final Part filePart = request.getPart("file");
InputStream filecontent = null;

然后在内try/catch

filecontent = filePart.getInputStream();

...并使用流中的数据。

这是上面教程的源代码(以防以后有人阅读时无法访问)。在这种情况下,它将文件写到文件服务器端,但是在您的情况下,您当然会填充您的文件imageData(我认为是您然后将其放入数据库中)。

@WebServlet(name = "FileUploadServlet", urlPatterns = {"/upload"})
@MultipartConfig
public class FileUploadServlet extends HttpServlet {

    private final static Logger LOGGER = 
            Logger.getLogger(FileUploadServlet.class.getCanonicalName());

    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 = 0;
            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;
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何在Java中获取文件的绝对路径

如何在PowerShell中基于相对路径或绝对路径获取绝对路径?

如何在flutter中获取文件的绝对路径

如何从InputStream获取Java文件的绝对路径?

获取java中URL的绝对路径

如何从SWT中的FileDialog获取文件的绝对路径?

如何从FileDialog获取绝对路径?

如何获取文件的绝对路径

如何在bash提示中显示绝对路径?

如何在Java中使用正确的字符编码获取绝对路径?

如何在Hadoop文件系统中获取绝对路径?

如何在Symfony2控制器中获取文件的绝对路径?

如何在Angular 2中获取当前页面的绝对路径?

如何在Android中获取内部存储的绝对路径

如何在react-native中获取文件的绝对路径?

如何在Linux中以编程方式获取给定相对路径的绝对路径?

如何在golang中解析相对路径到绝对路径?

如何在eclipse插件开发中获取特定插件的首选项文件的绝对路径?

如何在ASP.Net Core替代方法中获取Server.MapPath的绝对路径

如何在鼠标单击时获取QTreeWidget中当前所选项目的绝对路径

如何在 Gradle 构建脚本中获取 android 输出文件夹(绝对路径)

如何使用jfilechooser从Java中的文件名数组中获取多个文件选择的绝对路径

如何获取文件目录的绝对路径?

如何获取pathlib.Path对象的绝对路径?

Python:如何获取调用函数的文件的绝对路径?

如何从android目录URI获取绝对路径

拷贝文件时如何获取拷贝的绝对路径?

获取Eclipse中当前编辑文件的绝对路径

使用JavaScript在MVC中获取文件的绝对路径