Javascript

vue上传文件前台及后台接收【我】

本文主要是介绍vue上传文件前台及后台接收【我】,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

 

前台:

<html>
    <head>
        <meta charset="utf-8">
        <title></title>
        <script src="vue.js" type="text/javascript" charset="UTF-8"></script>
        <script src="jquery-3.6.0.js" type="text/javascript" charset="UTF-8"></script>
    </head>
    <body>
        <div id="app">
            {{message}}
            <input type="file" name="file" id="file" @change='onUpload'>//注意不能带括号
        </div>

    </body>
</html>

<script type="text/javascript">
    var vm = new Vue({
        el: '#app',
        data: {
            message: 'test',
        },
        methods: {
            //上传图片
            onUpload(e) {
                var formData = new FormData();
                formData.append('file', e.target.files[0]);
                formData.append('type', 'test');
                $.ajax({
                    // url: '/ShopApi/util/upload.weixun',
                    url: 'http://localhost:8083/order/process/upload',
                    type: 'POST',
                    dataType: 'json',
                    cache: false,
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: (res) => {
                        if (res.code === 200) {
                            alert(6)
                        }
                    },
                    error: function(err) {
                        alert("网络错误");
                    }
                });
            }
        }

    });
</script>

 

 

后台:

 @PostMapping("/upload")
    public Object batchImportUpload(@RequestParam("file") MultipartFile uploadFile) throws IOException {
        log.info("在线批量导入req:");
//      另一种方法参考
//      https://www.cnblogs.com/cheng2839/p/12660411.html
        //获取项目目录临时路径
        String staticPath = ClassUtils.getDefaultClassLoader().getResource("mapper").getPath();
        //生成临时目录
        File tempfolder = new File(staticPath + "/uploadFile/");
        if (!tempfolder.isDirectory()) {
            tempfolder.mkdirs();
        }
        //源文件名
        String oldName = uploadFile.getOriginalFilename();
        //新文件名
        String newName = System.currentTimeMillis() + oldName.substring(oldName.lastIndexOf("."));
        File newFile = new File(tempfolder, newName);
        //填充新文件
        uploadFile.transferTo(newFile);
        //新文件路径
        String newFileAllName = tempfolder + "/" + newName;
        log.info("临时文件全路径:{}" + newFileAllName);
        return new Response(ResultCode.OK, newFileAllName);

    }

 

这篇关于vue上传文件前台及后台接收【我】的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!