如何在Java中获取绝对路径

时间:2014-07-22 08:33:44

标签: java image file fileinputstream absolute-path

目前我正在从浏览器上传一张图片。现在在后端有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上传图片),那么如何获得这条绝对路径。

我尽力详细解释我的问题,如果有什么不清楚,请告诉我,我会尝试以其他方式解释。

2 个答案:

答案 0 :(得分:1)

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

这里有一个Java EE 6 tutoral文件上传: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(我将其带入数据库),然后填入数据库。 / p>

@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;
    }
}

答案 1 :(得分:1)

如果您使用浏览器提交表单,无法获取绝对路径,因为protocol(HTTP)
图像文件将附加到请求对象(没有任何绝对路径)。多数民众赞成!