使用JAVA上传图像并保存在文件夹中 [英] uploading images and saving in folder using JAVA

查看:131
本文介绍了使用JAVA上传图像并保存在文件夹中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$uploads_dir = '/uploads';
foreach ($_FILES["pictures"]["error"] as $key => $error) {
    if ($error == UPLOAD_ERR_OK) {
        $tmp_name = $_FILES["pictures"]["tmp_name"][$key];
        // basename() may prevent filesystem traversal attacks;
        // further validation/sanitation of the filename may be appropriate
        $name = basename($_FILES["pictures"]["name"][$key]);
        move_uploaded_file($tmp_name, "$uploads_dir/$name");
    }
}

这是使用PHP上传图像的方法. JAVA有相同的功能吗?我想上传图像并将其保存在文件夹中,但要使用JAVA.

This is how to upload images using PHP. Is there same function for JAVA. I want to upload image and save it in folder but using JAVA.

该操作应在表单提交时发生. 此上传没有servlet

The action should happened on form submit. No servlet for this upload

推荐答案

这可能有帮助:将所有文件从一个文件夹复制到另一个文件夹:

This might help: copies all files from one folder to another :

/**
 * Copy files from one directory to another.
 * @param sourceFile
 * @param destFile
 * @throws IOException
 */
public static void copyAllDirFiles(File fromDir, File toDir)
                                            throws IOException {
    //check if source is a directory 
    if (!fromDir.isDirectory()) {
        throw new IOException(fromDir + " directory not found.");
    }
    //if destination does not exit, create it 
    if (!toDir.exists()) {
        toDir.mkdir();
    }
    //get files from source 
    File[] files = fromDir.listFiles();
    for (File file : files) {
        InputStream in = new FileInputStream(file);
        OutputStream out = new FileOutputStream(toDir + "/"
                + file.getName());
        // Copy the bits from input stream to output stream
        byte[] buf = new byte[1024];
        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        in.close();
        out.close();
    }
}

这篇关于使用JAVA上传图像并保存在文件夹中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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