简单文件上传

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>upload</title>
</head>
<body>
    <form id="pForm" enctype="multipart/form-data">
        <input name="file" type="file" id="theFile"/>
    </form>
</body>
</html>


js

/*只是核心代码*/
function upLoadFile() {
    $("#theFile").change(function () {
        var filePath = $(this).val();
        if (!filePath.endsWith(".txt")){
            alert("请上传txt格式的文件");
            return false;
        }
        //确定上传
        var form = new FormData(document.getElementById("pForm"));
        $.ajax({
            url:fileImport.do,
            type:'POST',
            data:form,
            async:true,
            processData:false,
            contentType:false,
            scriptCharset:'utf-8',
            success:function (data) {
                var flag = data["data0"];
                if (flag){
                    alert("文件上传成功!");
                }else{
                    alert("文件上传失败!");
                }
            }
        });
    });
}

Java后台

@Controller
public class UpLoad {

    public String fileImport(@RequestParam("file") MultipartFile file, HttpServletRequest request, HttpServletResponse response){
        //获取文件件进行保存
        File fileDir = new File("D:\\xxxxx");
        if(!fileDir.exists()||!fileDir.isDirectory()){
            fileDir.mkdir();
        }
        String url = "被上传文件的全路径";
        //文件上传
        try {
            InputStream in = file.getInputStream();
            File file2 = new File(url);
            OutputStream out = new FileOutputStream(file2);
            byte[] b = new byte[1024];
            int len = 0;
            while((len = in.read(b))!=-1){
                out.write(b,0,len);
            }
            in.close();
            out.close();
            //读取每行内容
            FileInputStream fis = new FileInputStream(file2);
            InputStreamReader isr = new InputStreamReader(fis);
            BufferedReader br = new BufferedReader(isr);
            String str = null;
            while ((str = br.readLine())!=null){
                System.out.println(str);
            }
            br.close();
            isr.close();
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}


当然,需要先将commons相关jar包引入到项目中

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值