上传及接收pdf文件,使用pdfbox读取pdf文件内容

前端上传pdf文件

html

html 复制代码
<form class="layui-form">
	<div style="background-color: #ffffff" >
		<div style="padding: 30px">
			<div class="layui-form-item">
				<div class="layui-inline">
					<label class="layui-form-label"><label style="color: red">*</label>编号:</label>
					<div class="layui-input-inline">
						<input type="text" class="layui-input" name="orderNo" id="orderNo" >
					</div>
				</div>
			</div>
			<div class="layui-form-item">
				<div class="layui-inline">
					<label class="layui-form-label "><label style="color: red">*</label>上传文件:</label>
					<div class="layui-inline layui-input-inline">
						<input type="file" name="printFile" id="printFile">
					</div>
				</div>
			</div>
			<div class="layui-form-item">
				<div class="layui-input-block">
					<button type="button" class="layui-btn layui-btn-sm" id="save-button" onclick="save()">提交</button>
				</div>
			</div>
		</div>
	</div>
</form>

js

js 复制代码
function save(){
	var formData = new FormData();
	formData.appen("orderNo",$("#orderNo").val())
	var files = document.getElementById('printFile');
	if(files.files && files.files.length > 1){
		formData.append('file',files.files[0])
	}else{
		layer.msg("文件不能为空");
		return false;
	}
	formData.append('file',files.files[0])
	console.log("formData",formData)
	var url = ""
	HSoft.postMultipartForm(url), formData,function(res){
		console.log(res)
		if ("200" == res.code) {
			layer.msg(res.data);
			setTimeout(function(){
				 layer.closeAll('loading');
			},1000)
		} else {
			layer.msg("提交失败",res.msg);
		}
	});
}

this.postMultipartForm = function(url,formData,fn,errorCallback){
	$.ajax({
		type: "POST",
		url: url,
		data: formData,
		/**
		*必须false才会自动加上正确的Content-Type
		*/
		contentType: false,
		/**
		* 必须false才会避开jQuery对 formdata 的默认处理
		* XMLHttpRequest会对 formdata 进行正确的处理
		*/
		processData: false,
		error: function (XHR, textStatus, errorThrown) {
			console.log("XHR=" + XHR + "\ntextStatus=" + textStatus + "\nerrorThrown=" + errorThrown);
			if (errorCallback && typeof errorCallback == "function") {
				errorCallback({});
			}
		},
		success: function (data, textStatus) {
			if (fn && typeof fn == "function") {
				fn(data);
			}
		}
	});
};

后台接收文件

安装pdfbox依赖

xml 复制代码
<dependency>
	<groupId>org.apache.pdfbox</groupId>
	<artifactId>pdfbox</artifactId>
	<version>2.0.27</version>
</dependency>

controller

java 复制代码
@PostMapping("/uploadFile")
@ApiOperation("上传文件")
@ResponseBody
public CommonResult<String> uploadFile(@RequestParam("file") MultipartFile file, HttpServletRequest request){
    DataRespVO respVO = orderService.uploadFile(file,request);
    if(Objects.equals(respVO.getCode(), 200)){
        return CommonResult.success(respVO.getMessage());
    }
    return CommonResult.error(respVO.getCode(), respVO.getMessage());
}

service

java 复制代码
@Override
public DataRespVO uploadFile(MultipartFile file, HttpServletRequest request) {
    MultipartHttpServletRequest params=((MultipartHttpServletRequest) request);
   
    String orderNo = params.getParameter("orderNo ");
    if(HSoft.isEmpty(orderNo )){
        return new DataRespVO(ErrorCodeConstants.ORDER_NO_IS_EMPTY);
    }
    PDDocument document = null;
    try{
        // 读取标签文件内容
        String fileName = file.getOriginalFilename();
        document = PDDocument.load(file.getInputStream());
        int pageSize = document.getNumberOfPages();
        String text = "";
        // 一页一页读取
        for (int i = 0; i < pageSize; i++) {
            // 文本内容
            PDFTextStripper stripper = new PDFTextStripper();
            // 设置按顺序输出
            stripper.setSortByPosition(true);
            stripper.setStartPage(i + 1);
            stripper.setEndPage(i + 1);
            text = stripper.getText(document);
            System.out.println(text.trim());
        }
    }catch (Exception e){
        log.error(e.getMessage(),e);
        return new DataRespVO((new ErrorCode(10000001,"数据更新失败,"+e.getMessage())));
    } finally {
        try {
            if (document != null) {
                document.close();
            }
        } catch (IOException e) {
            log.error(e.getMessage(),e);
            return new DataRespVO((new ErrorCode(10000001,"数据更新失败,"+e.getMessage())));
        }
    }
    return new DataRespVO(ErrorCodeConstants.UPDATE_OK);
}
相关推荐
迷雾漫步者17 分钟前
Flutter组件————FloatingActionButton
前端·flutter·dart
向前看-44 分钟前
验证码机制
前端·后端
xlsw_1 小时前
java全栈day20--Web后端实战(Mybatis基础2)
java·开发语言·mybatis
神仙别闹2 小时前
基于java的改良版超级玛丽小游戏
java
燃先生._.2 小时前
Day-03 Vue(生命周期、生命周期钩子八个函数、工程化开发和脚手架、组件化开发、根组件、局部注册和全局注册的步骤)
前端·javascript·vue.js
黄油饼卷咖喱鸡就味增汤拌孜然羊肉炒饭2 小时前
SpringBoot如何实现缓存预热?
java·spring boot·spring·缓存·程序员
暮湫2 小时前
泛型(2)
java
超爱吃士力架2 小时前
邀请逻辑
java·linux·后端
南宫生2 小时前
力扣-图论-17【算法学习day.67】
java·学习·算法·leetcode·图论