栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java+ajax实现文件上传

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java+ajax实现文件上传

1 文件上传

利用Java+ajax实现文件上传,这里介绍两种提交方法,第一种是file提交,第二种是base64提交

1.1 file方式

1.1.1 FileNameUtils

public class FileNameUtils{
    
    public static String getSuffixByStr(String fileName){
        return fileName.substring(fileName.lastIndexOf("."));
    }
​
    
    public static String getFileName(String fileOriginName){
        return UUIDUtils.getUUID() + FileNameUtils.getSuffixByStr(fileOriginName);
    }
}

1.1.2 MyFileUtils

public class MyFileUtils {
    
    public static boolean uploadFile(MultipartFile file, String path, String fileName){
        // 生成新的文件名
        String realPath = path + "/" + FileNameUtils.getFileName(fileName);
        //使用原文件名
        //String realPath = path + "/" + fileName;
​
        File dest = new File(realPath);
​
        //判断文件父目录是否存在
        if(!dest.getParentFile().exists()){
            dest.getParentFile().mkdir();
        }
​
        try {
            //保存文件
            file.transferTo(dest);
            return true;
        } catch (IllegalStateException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
​
    }
}

1.1.3 Controller调用

String loadpath="D:/uploadflie/images/"+System.currentTimeMillis();
boolean re= MyFileUtils.uploadFile(file,loadpath,file.getOriginalFilename());

1.1.4 ajax请求

以上传头像为例,需要把input[type=file]的vale()封装成表单数据,然后提交而且processData和contentType都要设置

var file=document.getElementById("upfile").files[0];
        var fordate=new FormData();
        fordate.append("file",file);//封装为表单数据
        $.ajax({
            url:"/user/uploadfile",
            type: "POST",
            data:fordate,
            dataType: 'json',
            processdata: false,
            contentType : false,
            success:function (data) {
                if(data.status ==1){
​
                }
            }
        })
1.2 base64方式

1.2.1 base64Utils

public class base64Utils {
​
    
    public static boolean decode(String base64Str,String filePath,String fileName){
        File file = null;
        //创建文件目录
        File  dir=new File(filePath);
        if (!dir.exists() && !dir.isDirectory()) {
            dir.mkdirs();
        }
        BufferedOutputStream bos = null;
        java.io.FileOutputStream fos = null;
​
        byte[] b = null;
        base64Decoder decoder = new base64Decoder();
        try {
            b = decoder.decodeBuffer(replaceEnter(base64Str));
            //window
            //file=new File(filePath+"\"+fileName);
            //linux
            file=new File(filePath+"/"+fileName);
            fos = new java.io.FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(b);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    return false;
                }
            }
        }
        return true;
    }
​
    
    public static String encode(byte[] image){
        base64Encoder decoder = new base64Encoder();
        return replaceEnter(decoder.encode(image));
    }
​
    public static String encode(String uri){
        base64Encoder encoder = new base64Encoder();
        return replaceEnter(encoder.encode(uri.getBytes()));
    }
​
    
​
    public static byte[] imageTobyte(String path){
        byte[] data = null;
        FileImageInputStream input = null;
        try {
            input = new FileImageInputStream(new File(path));
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            byte[] buf = new byte[1024];
            int numBytesRead = 0;
            while((numBytesRead = input.read(buf)) != -1){
                output.write(buf, 0, numBytesRead);
            }
            data = output.toByteArray();
            output.close();
            input.close();
​
        } catch (Exception e) {
            e.printStackTrace();
        }
​
        return data;
    }
​
    public static String replaceEnter(String str){
        String reg ="[n-r]";
        Pattern p = Pattern.compile(reg);
        Matcher m = p.matcher(str);
        return m.replaceAll("");
    }
​
}

1.2.2 后台调用

前面使用的FileNameUtils工具类可以用于设置上传文件名,然后再调用base64Utils进行文件上传。代码如下

   SimpleDateFormat format=new SimpleDateFormat("YYYYMMDDHHmmss");
   String loadpath="D:/uploadflie/images/";
   String timeDir=format.format(System.currentTimeMillis());
   loadpath+="/";
   loadpath+=timeDir;
   String newfliename= FileNameUtils.getFileName(filename);
   String newfile=file.substring(file.lastIndexOf(",")+1);//去掉base64前端标识,到’,‘处
   boolean re= base64Utils.decode(newfile,loadpath,newfliename);

注意:前端传过来的base64文件夹带有前端标识,需要处理以后使用filename是前端传来的文件名字,方便获取文件类型,

1.2.3 前端base64处理 

var dateURL="";
    var file=document.getElementById("upfile").files[0];
    var reader=new FileReader();
    var $image = $('#img_container img');
    reader.readAsDataURL(file);
    reader.onload=function (e) {
        dateURL=e.target.result;
    }

1.2.4 ajax请求

 var base64file=$("#tuoxiang").prop("src");//已转base64文件
        var filename=$("#upfile").val();//input[type=file]获取文件名称
        $.ajax({
            url:"/user/uploadBybase64",
            type: "POST",
            dataType: "json",
            data:{"file":base64file,"filename":filename},
            success:function (data) {
                
            }
​
        })
    })

ps:如果需要源码的朋友,可以加QQ群获取,群:1039603877

--------------------------------------------------------------------------------------------

QQ群:1039603877,本群创建于2020/2/3:  本群原为1999人大群,主要是进行java开发技术交流,里面有java开发的业界大佬、牛人,很多群友都是CTO或者技术负责人,同时也有关于java岗位招聘等消息。欢迎大家进群学习和交流

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/785032.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号