Java如何实现文件的上传下载,并对其文件解析

  • Post author:
  • Post category:java


package com.atguigu.mybatisplus.controller;


import com.atguigu.mybatisplus.enums.CsvEnum;
import com.atguigu.mybatisplus.enums.SexEnum;
import com.atguigu.mybatisplus.mapper.UserMapper;
import com.atguigu.mybatisplus.pojo.User;
import com.atguigu.mybatisplus.service.UserService;
import com.atguigu.mybatisplus.utils.CodeUtil;
import com.atguigu.mybatisplus.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.net.MalformedURLException;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Scanner;

import static javafx.scene.input.KeyCode.T;

@RestController
@RequestMapping("/file")
@Slf4j
public class CsvFileUploadDownLoad {

    @Autowired
    private UserService userService;

    @Autowired
    private UserMapper userMapper;

    @PostMapping("/upload")
    @Transactional(rollbackFor = Exception.class)
    public R uploadCsvFile(@RequestParam("file") MultipartFile[] files ){
        if(files.length==0||files == null){
           return R.error(1000,"请上传文件");
        }
        for(MultipartFile file:files){
            if(file.isEmpty()){
                return R.error(1003,"请上传文件");
            }
            if(!file.getOriginalFilename().matches("^.+\\.(?i)(csv)$")){
                return R.error(1002,"请上传正确格式的csv文件");
            }
            String fileName = file.getOriginalFilename();
            System.out.println(File.separator+"============================");//  \
           /* String uploadDir = "D:\\whupload";
            File uploadDirFile = new File(uploadDir);
            File[] listFiles = uploadDirFile.listFiles();
            for (File listFile : listFiles) {
                if(fileName.equals(listFile.getName())){
                    return R.error(1004,"文件库中已经存在相同文件名文件");
                }
            }*/
            String uploadDest = "D:\\whupload"+ File.separator+fileName;
            File destFile = new File(uploadDest);
            try {
                file.transferTo(destFile);
                InputStream inputStream = new FileInputStream(destFile);
                String code = CodeUtil.codeString(destFile);
                Scanner scanner = new Scanner(inputStream, code);
                String firstLine = scanner.next();
                String[] firstTitle = firstLine.split(",");
                ArrayList<User> users = new ArrayList<>();
                while (scanner.hasNextLine()){
                    System.out.println(scanner.hasNextLine());
                    String nextLine = scanner.next();
                    String[] nextLines = nextLine.split(",");
                    User user = new User();
                    for(int i = 0;i<firstTitle.length;i++){
                        CsvEnum csvEnum = CsvEnum.getSetMethodByTitle(firstTitle[i].replace("\uFEFF",""));
                        try {
                            String s = csvEnum.getField();
                            Object value=null;
                            Class fieldClass=null;
                            switch (s){
                                case "String":
                                    fieldClass = String.class;
                                    value = nextLines[i].toString();
                                    break;
                                case "Integer":
                                    fieldClass = Integer.class;
                                    value = Integer.parseInt(nextLines[i]);
                                    break;
                                case "enum":
                                    fieldClass = SexEnum.class;
                                    value = SexEnum.getBySexName(nextLines[i]);
                                    break;
                            }
                            Method method = user.getClass().getMethod(csvEnum.getSetMethod(),fieldClass);
                            method.invoke(user,value);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    users.add(user);
                }
                userService.saveBatch(users);
                scanner.close();
            } catch (IOException e) {
                return R.error(1001,"上传文件失败");
            }
        }
        return R.ok();
    }


        /**
         * 10.下载文件
         */
        @RequestMapping("/download")
        @ResponseBody
        public ResponseEntity<Resource> downloadFile(@RequestParam("filename") String fileName){
            try {
                Resource resource=new UrlResource(
                        //拼接下载的文件的原路径
                        Paths.get("D:/whupload"+File.separator+fileName).toUri());
                if(resource.exists() && resource.isReadable()){
                    return ResponseEntity.ok()
                            .header(HttpHeaders.CONTENT_TYPE, "application/octet-stream")
                            .header(HttpHeaders.CONTENT_DISPOSITION,"attachment;filename=\""+
                                    resource.getFilename()+"\"").body(resource);

                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
                log.debug(e.getMessage());
            }
            return null;
        }
}



package com.atguigu.mybatisplus.pojo;

import com.atguigu.mybatisplus.enums.SexEnum;
import com.baomidou.mybatisplus.annotation.*;
import lombok.*;

import javax.validation.constraints.Email;

/**
 * Date:2022/6/29
 * Author:lxd
 * Description:
 */
@Data
//设置实体类所对应的表名
//@TableName("t_user")
public class User {

    //将属性所对应的字段指定为主键
    //@TableId注解的value属性用于指定主键的字段
    //@TableId注解的type属性设置主键生成策略
    //@TableId(value = "uid", type = IdType.AUTO)
    @TableId(value = "id",type = IdType.AUTO)
    private Long id;

    //指定属性所对应的字段名
    @TableField("name")
    private String name;

    private Integer age;

    @Email
    private String email;

    private SexEnum sex;

    @TableLogic
    private Integer isDeleted;

}



package com.atguigu.mybatisplus.enums;

import com.baomidou.mybatisplus.annotation.EnumValue;
import lombok.Getter;

/**
 * Date:2022/6/29
 * Author:lxd
 * Description:
 */
@Getter
public enum SexEnum {
    MALE(1, "男"),
    FEMALE(2, "女");

    @EnumValue //将注解所标识的属性的值存储到数据库中
    private Integer sex;
    private String sexName;

    SexEnum(Integer sex, String sexName) {
        this.sex = sex;
        this.sexName = sexName;
    }

    public static SexEnum getBySexName(String sexName){
        for (SexEnum sexEnum:SexEnum.values()){
            if(sexName.equals(sexEnum.getSexName())){
                return sexEnum;
            }
        }
        return null;
    }
}

```
package com.atguigu.mybatisplus.enums;

import lombok.AllArgsConstructor;
import lombok.Getter;


@Getter
@AllArgsConstructor
public enum CsvEnum {

    NAME("name","setName","String"),
    AGE("age","setAge","Integer"),
    EMAIL("email","setEmail","String"),
    SEX("sex","setSex","enum");
    private String title;
    private String  setMethod;
    private String field;
    public static CsvEnum getSetMethodByTitle(String title){
        System.out.println(title);
        for (CsvEnum csvEnum:CsvEnum.values()){
//            System.out.println(csvEnum.getTitle());
            if(csvEnum.getTitle().equals(title)){
                return csvEnum;
            }
        }
        return null;
    }
}
```




package com.atguigu.mybatisplus.utils;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;

public class CodeUtil {
    public static String codeString(File fileName) {
        String code = "UTF-8";
        try {
            BufferedInputStream bin = new BufferedInputStream(new FileInputStream(fileName));
            int p = (bin.read() << 8) + bin.read();
            bin.close();
            switch (p) {
                case 0xefbb:
                    code = "UTF-8";
                    break;
                case 0xfffe:
                    code = "Unicode";
                    break;
                case 0xfeff:
                    code = "UTF-16BE";
                    break;
                default:
                    code = "GBK";
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return code;
    }
}



版权声明:本文为lxd1373006963原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。