文件下载 前端后端

前端用element

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Document</title>

    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">

    <script src="/vue.js"></script>

    <script src="/axios-0.18.0.js"></script>

    <!-- 引入组件库 -->

    <script src="https://unpkg.com/element-ui/lib/index.js"></script>

</head>

<body>

    <div id="zy1">

        你的姓名:<input v-model="name" /><br>

        <input type="file" v-model="tp" />

        [{{tp}}]

        <!-- <br>

        <input type="button" value="上传" @click="uploading" /> -->

        <br>

        <br>

        <el-upload class="upload-demo" action="http://127.0.0.1:8080/up/loading" :on-preview="handlePreview"

            :on-remove="handleRemove" :before-remove="beforeRemove" multiple :limit="3" :on-exceed="handleExceed"

            :file-list="fileList">

            <el-button size="small" type="primary">点击上传</el-button>

            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>

        </el-upload>

    </div>

    <script>

        new Vue({

            el: "#zy1"

            , data: {

                name: ''

                , tp: ''

                , fileList: []

            },

            methods: {

                uploading: function () {

                    var formData = new FormData();

                    formData.append('File', this.tp);

                    if (this.tp == '') {

                        alert("不能上传空文件")

                        return fales;

                    }

                    axios.post("http://127.0.0.1:8080/up/loading", {

                        params: {

                            name: this.name,

                            file: formData

                        }

                    }, { headers: { 'Content-Type': 'multipart/form-data' } }).then((ret) => {

                        console.log(ret.data)

                    })

                },

                handleRemove(file, fileList) {

                    console.log(file, fileList);

                },

                handlePreview(file) {

                    console.log(file);

                },

                handleExceed(files, fileList) {

                    this.$message.warning(`当前限制选择 3 个文件,本次选择了 ${files.length} 个文件,共选择了 ${files.length + fileList.length} 个文件`);

                },

                beforeRemove(file, fileList) {

                    return this.$confirm(`确定移除 ${file.name}?`);

                }

            }

        })

    </script>

</body>

</html>

后端boot

package com.xxx.pro;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
@CrossOrigin(origins="*")
@Controller
@RequestMapping("/up")
public class io {


        @RequestMapping("/loading")
        @ResponseBody
        public String uploading(@RequestParam(name = "file",required=false)  MultipartFile file ) {
            if (file.isEmpty()) {
                return "文件为空";
            }
            // 获取文件名
            String fileName = file.getOriginalFilename();
            System.out.println("上传的文件名为:" + fileName);
            // 获取文件的后缀名
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            System.out.println("上传的后缀名为:" + suffixName);
            // 文件上传后的路径
            String filePath = "D://";
            File dest = new File(filePath + fileName);
            // 检测是否存在目录
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            try {
                file.transferTo(dest);
                return "上传成功";
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return "上传失败";
        }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
多文件上传指的是一次上传多个文件,而不是一次只上传一个文件。下面我会分别介绍前端后端的实现方式。 前端实现: 前端通常使用HTML中的`<input type="file" multiple>`元素来实现多文件上传功能,其中`multiple`属性表示允许选择多个文件。用户选择文件后,前端会将文件信息存储在FormData对象中,然后通过ajax请求将FormData对象发送到后端。 示例代码: ```html <form id="file-form"> <input type="file" id="file-input" multiple> <button type="submit">上传文件</button> </form> <script> const form = document.getElementById('file-form'); const fileInput = document.getElementById('file-input'); form.addEventListener('submit', (e) => { e.preventDefault(); const formData = new FormData(); for (let i = 0; i < fileInput.files.length; i++) { formData.append('files', fileInput.files[i]); } fetch('/upload', { method: 'POST', body: formData }) .then(response => { console.log(response); }) .catch(error => { console.error(error); }); }); </script> ``` 后端实现: 后端通常使用框架提供的文件上传中间件来处理文件上传,例如Node.js中的`multer`中间件。后端接收到前端发送的FormData对象后,通过中间件解析出文件信息,然后将文件保存到指定目录。 示例代码(使用Express框架和multer中间件): ```javascript const express = require('express'); const multer = require('multer'); const app = express(); const upload = multer({ dest: 'uploads/' }); app.post('/upload', upload.array('files'), (req, res) => { console.log(req.files); res.send('上传成功'); }); app.listen(3000, () => { console.log('服务已启动'); }); ``` 在上面的示例中,`multer`中间件的`upload.array('files')`表示接收名为`files`的文件数组。在处理上传成功后,后端会返回一个响应,告诉前端上传成功。 需要注意的是,在上传大文件时,为了避免内存溢出,通常需要对文件进行分片上传和断点续传等优化处理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值