读取前端上传文件和下载文件

代码如下:

@Service
@Slf4j
public class WhiteService {

    public List<String> readFromFile(WhiteFile file) throws IOException {
        List<String> list = new ArrayList<String>();
        //1.判断文件是否存在
        if(file.getFile().isEmpty()||file.getFile().getSize()<0){
            log.warn("file data got zero :{}",file.getName());
            return new ArrayList<>();
        }
        //2.解析文件
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(file.getFile().getInputStream()));
        try{
            String lineTxt;
            while((lineTxt = bufferedReader.readLine()) != null){
                list.add(lineTxt);
            }
            bufferedReader.close();

        }catch (Exception e){
            log.error(e.getMessage());
        }finally {
            bufferedReader.close();
        }

        return list;
    }
}

public class WhiteFile {

    @JSONField(serialize = false)
    private MultipartFile file;

    private String key;
    private String name;

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public MultipartFile getFile() {
        return file;
    }

    public void setFile(MultipartFile file) {
        this.file = file;
    }

}

下载文件 

private void createTxtFile(HttpServletResponse response, String filename, String Metadata) {
        // 让servlet用UTF-8转码,默认为ISO8859
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/csv");
        response.addHeader("Content-Disposition",String.format("attachment; filename=\"%s.csv\"", filename));
        try {
            OutputStream outputStream = response.getOutputStream();
            String[] strings=Metadata.split(",");
            for(int i=0;i<strings.length-1;i++){
                outputStream.write(strings[i].getBytes(StandardCharsets.UTF_8));
                outputStream.write(",".getBytes(StandardCharsets.UTF_8));
                outputStream.write("\r\n".getBytes());
            }
            outputStream.write(strings[strings.length-1].getBytes(StandardCharsets.UTF_8));
            outputStream.write(",".getBytes(StandardCharsets.UTF_8));
            outputStream.flush();
            outputStream.close();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值