当前位置: 首页>前端>正文

element Upload 去除白框 element upload data

一、前端上传

前端主要使用elementUI中的el-upload标签作为上传控件,通过axios发送post请求到后端,将文件上传到服务器中;需要注意的点:前端向后端发送的文件需要以formData格式存储,文件需要通过val.raw的方式将数据传给formData对象

  • body标签代码:
<!-- 上传对话框 -->
			<el-dialog title="上传" :visible.sync="dialogOfUpload" width="35%" style="text-align: center;">
				<el-upload class="upload-demo" action="#" drag multiple :headers="headers" :auto-upload="false"
				 :file-list="fileList" :on-change="handleChange">
					<i class="el-icon-upload"></i>
					<div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
					<div class="el-upload__tip" slot="tip">上传Excel格式文件</div>
				</el-upload>
				<div slot="footer" class="dialog-footer">
					<el-button @click="dialogOfUpload = false">取 消</el-button>
					<el-button type="primary" @click="confirmUpload()">上 传</el-button>
				</div>
			</el-dialog>
  • action属性为上传的地址,这里用#号忽略了,使用axios发送请求;
  • headers为请求头,写死为'Content-Type': 'multipart/form-data'
  • auto-upload为是否自动上传,设置为false,关闭自动上传;
  • file-list为上传的文件列表,为数组的形式;
  • on-change,文件状态改变时的钩子,添加文件、上传成功和上传失败时都会被调用;和handleChange函数绑定,文件变化时给fileList赋值,fileList通过这种方式获取值;
  • date数据代码:
data() {
				return {
				    dialogOfUpload: false,
					fileList: [],
					headers: {
						'Content-Type': 'multipart/form-data'
					}
				}
			},
  • method方法代码:
  • fileList存放上传的文件列表
  • headers设置请求头
methods: {
				handleChange(file, fileList) { //文件数量改变
					this.fileList = fileList;
				},

				confirmUpload() { //确认上传
					var param = new FormData();
					this.fileList.forEach(
						(val, index) => {
							param.append("file", val.raw);
						}
					);

					axios.post("/export/upload", param).then(responce => {});

					this.$message({
						message: "上传成功!",
						duration: 1000
					});
				},
				}
  • fileList通过handleChange函数触发来获取值,函数的形参有两个,参考官方文档,其中file为单个文件,fileList为文件集合;
  • 点击确认按钮时触发confirmUpload函数,将上传的文件发送到后端;
  • 运用axios发送post请求,发送的地址为/export/upload,完整路径是http://localhost:8080/export/upload
  • 发送的数据应为FormDate格式,因此新建一个FormDate格式的param变量存放上传的文件列表;
  • 不能直接将fileList数组赋给param变量,应该对fileList进行forEach遍历,通过val.raw来取得文件内容赋给param变量,即param.append("file", val.raw);
  • 完成

element Upload 去除白框 element upload data,element Upload 去除白框 element upload data_upload,第1张

element Upload 去除白框 element upload data,element Upload 去除白框 element upload data_java_02,第2张

① 点击上传按钮

element Upload 去除白框 element upload data,element Upload 去除白框 element upload data_java_03,第3张

② 上传文件

element Upload 去除白框 element upload data,element Upload 去除白框 element upload data_上传_04,第4张

③ 点击上传

二、后端接收

后端代码如下:

package com.han.sale.handler;

import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.han.common.entity.ResponseBean;
import com.han.common.entity.StatusCode;
import com.han.common.util.ReadExcel;
import com.han.common.util.Word;
import com.han.sale.entity.ExportList;
import com.han.sale.service.CodeNumberService;
import com.han.sale.service.ExportListService;
import com.han.sale.service.OrderGoodsService;
import com.han.sale.service.OrderService;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;

@Controller
@RequestMapping("export")
public class ExportListHandler {

    @Resource(name = "orderService")
    private OrderService orderService;

    @Resource(name = "orderGoodsService")
    private OrderGoodsService orderGoodsService;

    @Resource(name = "exportListService")
    private ExportListService exportListService;

    @Resource(name = "codeNumberService")
    private CodeNumberService codeNumberService;

    @GetMapping("query")
    public ResponseEntity query(ExportList exportList, @RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "10") Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        if ("全部".equals(exportList.getGoodsstatus())) exportList.setGoodsstatus(null);
        List<ExportList> lists = exportListService.getAllBy(exportList);
        PageInfo<ExportList> pageInfo = new PageInfo<>(lists);
        return ResponseEntity.ok(new ResponseBean(StatusCode.OPERATE_SUCCESS, pageInfo));
    }

    @GetMapping("update")
    public ResponseEntity update(ExportList exportList) {
        exportList.setCreatetime(null);
        int i = exportListService.updateByPrimaryKeySelective(exportList);
        if (i > 0) return ResponseEntity.ok(new ResponseBean(StatusCode.OPERATE_SUCCESS, null));
        else return ResponseEntity.ok(new ResponseBean(StatusCode.OPERATE_FAILED, null));
    }

    @GetMapping("check")
    public ResponseEntity check() {
        List<ExportList> exportLists = exportListService.getAll();
        //遍历所有的出库单,根据IMEI,将商品状态同步为order_goods表中对应的商品状态
        for (ExportList exportList : exportLists) {
            ExportList list = new ExportList();
            list.setExportid(exportList.getExportid());
            list.setGoodsstatus(orderGoodsService.selectByIMEI(exportList.getImei()).getGoodsstatus());
            exportListService.updateByPrimaryKeySelective(list);
        }
        return ResponseEntity.ok(new ResponseBean(StatusCode.OPERATE_SUCCESS, null));
    }

    @Resource
    private Word word;

    @PostMapping("generate")
    public ResponseEntity generate(@RequestBody String str) throws Exception {
        List<ExportList> lists = JSONArray.parseArray(str, ExportList.class);
        ExportListHandler.NAME = word.export(lists);
        return ResponseEntity.ok(new ResponseBean(StatusCode.OPERATE_SUCCESS, null));
    }

    //    E:\maven\shopping\target\shopping\WEB-INF\download\出库单1039.docx
    private static String NAME;

    @GetMapping("download")
    public HttpServletResponse download(HttpServletResponse response) throws Exception {
        File file = new File(ExportListHandler.NAME);
        String name = file.getName();
        BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file));
        byte[] bytes = new byte[inputStream.available()];
        inputStream.read(bytes);
        inputStream.close();
        // 清空response
        response.reset();
        // 设置response的Header
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(new String(name.getBytes()), "UTF-8"));
        response.addHeader("Content-Length", "" + file.length());
        BufferedOutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
        response.setContentType("application/octet-stream");
        outputStream.write(bytes);
        outputStream.flush();
        outputStream.close();
        //删除服务器上的临时文件
        file.delete();
        return response;
    }

    private static String UPLOAD_PATH;

    @Resource
    private ReadExcel readExcel;

    @PostMapping("upload")
    public ResponseEntity upload(@RequestParam MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws Exception {
        //        tb_export.xlsx
        String filename = file.getOriginalFilename();
        //        E:\maven\shopping\target\shopping\upload\
        String upload = request.getServletContext().getRealPath("upload/");

        File fileDir = new File(upload);
        File[] files = fileDir.listFiles();
        for (File f : files) {
            f.delete();
        }

        String path = upload + filename;
        File filePath = new File(path);
        ExportListHandler.UPLOAD_PATH = path;
        BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(filePath));
        outputStream.write(file.getBytes());
        outputStream.flush();
        outputStream.close();
        //遍历读取Excel
        readExcel.read(upload);
        return null;
    }


}
  • 前端通过axios发送给后端,后端在@PostMapping("upload")中接收;
  • 需要注意,upload的方法形参为@RequestParam MultipartFile file,因此前端传来的需要有形参file,即param.append("file", val.raw);
  • String filename = file.getOriginalFilename();获取上传的文件名称;
  • String upload = request.getServletContext().getRealPath("upload/");在当前类的路径下加一个upload文件夹,作为上传文件的临时目录,绝对路径为:E:\maven\shopping\target\shopping\upload\
  • File fileDir = new File(upload);以上述路径创建File对象;
  • File fileDir = new File(upload); File[] files = fileDir.listFiles(); for (File f : files) { f.delete(); } 遍历upload文件夹,删除其下所有文件;
  • 通过缓存区输出流BufferedOutputStream的对象来将上传的文件写入upload文件夹中;
  • BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(filePath));其中,BufferedOutputStream的参数为FileOutputStream对象,而FileOutputStream的参数为File对象,而File的参数可以设为所上传文件的绝对路径E:\maven\shopping\target\shopping\upload\tb_order.xlsx
  • outputStream.write(file.getBytes());通过outputStream对象的write()方法将文件写入;

element Upload 去除白框 element upload data,element Upload 去除白框 element upload data_java_05,第5张

  • outputStream.flush(); outputStream.close();刷新及关闭输出流
  • readExcel.read(upload);后续读取Excel文件内容到数据库中的操作;



https://www.xamrdz.com/web/2kx1934882.html

相关文章: