JAVA上传pdf文件

416 阅读1分钟

“携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第11天,点击查看活动详情

生命无罪,健康万岁,我是laity。

我曾七次鄙视自己的灵魂:

第一次,当它本可进取时,却故作谦卑;

第二次,当它在空虚时,用爱欲来填充;

第三次,在困难和容易之间,它选择了容易;

第四次,它犯了错,却借由别人也会犯错来宽慰自己;

第五次,它自由软弱,却把它认为是生命的坚韧;

第六次,当它鄙夷一张丑恶的嘴脸时,却不知那正是自己面具中的一副;

第七次,它侧身于生活的污泥中,虽不甘心,却又畏首畏尾。

配置文件

jeecg :
  path :
    #pdf路径
    pdf: D:\\opt\\webapp\\pdf

Controller层

    /**
     * 上传pdf文件
     */
    @PostMapping(value = "/uploadPdfFile")
    public Result<Object> uploadPdfFile(@RequestParam("file") @NotNull(message = "pdf文件不能为空")  MultipartFile file) {
        Result<Object> result = new Result<>();
        String message="";
        try {
            pdfService.uploadPdfFile(file);
            message = StrUtil.format("上传pdf文件成功");
            result.setSuccess(true);
        } catch (IOException e) {
            message = StrUtil.format("上传pdf文件失败");
            result.error500(message);
            e.printStackTrace();
        }
        return result;
    }

Service层

@Value("${jeecg.path.pdf}")
private String pdfPath;
 
 
public void uploadRiskClause(MultipartFile file) throws IOException {
        //上传内容
        File files = new File(pdfPath);
        //装备目标文件地址
        File dir = new File(pdfPath).getAbsoluteFile();
        log.info("目标文件地址dir = {}",dir);
        if (!dir.exists()) {
            dir.mkdirs(); //不存在就创建文件夹
        }
        //获取上传文件的名字
        String OriginalFilename = file.getOriginalFilename();
        String fileName = FileNameUtil.getName(OriginalFilename);
        //获取文件类型
        String type = FileTypeUtil.getType(file.getInputStream());
        log.info("上传文件名称-{},文件类型-{}",fileName,type);
        if(!"pdf".equals(type)){
            throw new JeecgBootException("文件仅支持pdf格式");//jeecgBoot框架自定义异常
        }
        if (fileName.length() >= 80) {
            throw new JeecgBootException("文件名过长,请检查文件名称保证不超过80个字符");//jeecgBoot框架自定义异常
        }
        //存在就关联文件夹 和 文件名字
        File dest = new File(dir, fileName);
        file.transferTo(dest);
    }

整合

package com.sinosoft.ie.controller;
 
import com.sinosoft.ie.model.ItemFiles;
import com.sinosoft.ie.service.ItemFilesService;
import com.sinosoft.ie.util.IdUtils;
import com.sinosoft.ie.util.ResponseMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
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.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
 
/**
 * @Author 庭前云落
 * @Date 2021/3/4 9:41
 * @Description
 */
@Slf4j
@RestController
@RequestMapping("/ItemFilesController")
public class ItemFilesController {
 
    @Resource
    private ItemFilesService itemFilesService;
 
    @Value("D:/")
    private String UPLOADED_FOLDER;
 
 
    @GetMapping("/download.do")
    public ResponseMessage downloadFile(@RequestParam("fileId") String fileId,  HttpServletResponse response) throws UnsupportedEncodingException {
 
        //根据ID查出对应文件的文件名
        ItemFiles itemFiles = itemFilesService.selectOneByFileId(fileId);
        String fileName = itemFiles.getName();
 
        if (fileName != null) {
            if (fileName.contains("/") || fileName.contains("\\")) {
                return null;
            }
            File file = new File(UPLOADED_FOLDER, fileName);
            if (file.exists()) {
                response.setContentType("application/force-download");// 设置强制下载不打开
                response.addHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));// 设置文件名
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                    System.out.println("success");
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return null;
    }
 
    @PostMapping("/upload.do")
    public ResponseMessage singleFileUpload(@RequestParam("file") MultipartFile file,HttpServletRequest request) {
        //往数据库里面存的数据
        Integer intId = IdUtils.getIntId();
        String itemId = request.getHeader("itemId");
        String userId = request.getHeader("userId");
 
        String originalFileName = file.getOriginalFilename().toString();
        if (!file.getName().matches("^.+\\.(?i)(pdf)$") && !file.getName().matches("^.+\\.(?i)(PDF)$") &&
                !originalFileName.matches("^.+\\.(?i)(pdf)$") && !originalFileName.matches("^.+\\.(?i)(PDF)$")
        ) {
            return null;
        }
 
        try {
            byte[] bytes = file.getBytes();
            if (file.getName() == null) {
                originalFileName = new String(file.getName().getBytes(), "UTF-8");
            }
 
            //要求上传的PDF文件名不重复,所以设置成随机的ID
            String filePath = UPLOADED_FOLDER + File.separator + String.valueOf(intId)+".pdf";
            File dest = new File(filePath);
            if (!dest.getParentFile().exists()) { //判断文件父目录是否存在
                dest.getParentFile().mkdir();
            }
            Path path = Paths.get(filePath);
            Files.write(path, bytes);
 
            //相关数据保存到数据库
            itemFilesService.add(String.valueOf(intId),originalFileName,itemId,userId);
 
            return ResponseMessage.createSucResponseMessage("PDF文件上传成功");
        } catch (Exception e) {
            log.error("PDF上传文件异常",e);
            return ResponseMessage.createErrResponseMessage("PDF上传文件失败");
        }
    }
}