Java处理文件时常用的文件类型及对应的contentType

2023.3.02
项目管理系统中对项目文档的处理
本来全部设置的是二进制流,发现下载后没有文件类型和文件名称
对应的解决办法:
上传、下载的时候对文件类型进行说明
上传:

private String upload(String existLobId, String contentType, MultipartFile multiFile) throws RuntimeException {
        String lobId = null;
        try {
            byte[] all = multiFile.getBytes();
            //如果已有lobId则删除原文档
            if (StringUtils.isNotBlank(existLobId)) {
                lobDbServiceClient.delete(existLobId);
            }
            lobId = lobDbServiceClient.add(all, contentType, "/xmgl/doc").getSuccRsValue();
        } catch (IOException e) {
            log.error("附件存小文件系统异常", e);
            throw new RuntimeException("附件存小文件系统异常");
        }
        return lobId;

下载:

public HttpServletResponse download(String id, HttpServletResponse response) {
        DocData docData = getDocById(id);
        FileOutputStream fileOutputStream = null;
        ServletOutputStream outStream = null;
        try {
            // 写成文件
            String fileName = docData.getFileName();
            String contentType = "application/octet-stream";
            RetVal val = getContentType(fileName);
            if (val.isSuccess()) {
                contentType = val.getValue().toString();
            }
            File file = new File(fileName);
            fileOutputStream = new FileOutputStream(file);
            // 以流的形式下载文件。
            byte[] fileContent = lobDbServiceClient.getLob(docData.getLobId()).getSuccRsValue().getContent();
            fileOutputStream.write(fileContent);
            fileOutputStream.close();
            // 设置response的Header
            response.setContentType(contentType);
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            response.addHeader("Content-Length", "" + fileContent.length);
            //输出流文件
            outStream = response.getOutputStream();
            InputStream fis = new FileInputStream(file);
            byte[] buffer = new byte[1024];
            int len;
            while ((len = fis.read(buffer)) > 0) {
                outStream.write(buffer, 0, len);
            }
            fis.close();
        } catch (IOException ex) {
            log.error("文件读取异常", ex);
            ex.printStackTrace();
        } finally {
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outStream != null) {
                try {
                    outStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return response;
    }
/**
     * 根据不同文件类型设置contentType
     */
    private RetVal getContentType(String fileName) {
        String contentType = null;
        String ext = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
        switch (ext) {
            case "html":
            case "htm":
                contentType = "text/html; charset=utf-8";
                break;
            case "txt":
                contentType = "text/plain; charset=utf-8";
                break;
            case "pdf":
                contentType = "application/pdf";
                break;
            case "doc":
                contentType = "application/msword";
                break;
            case "docx":
                contentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
                break;
            case "xls":
                contentType = "application/vnd.ms-excel";
                break;
            case "xlsx":
                contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                break;
            case "ppt":
                contentType = "application/vnd.ms-powerpoint";
                break;
            case "pptx":
                contentType = "application/vnd.openxmlformats-officedocument.presentationml.presentation";
                break;
            case "wps":
                contentType = "application/vnd.ms-works";
                break;
            case "xml":
                contentType = "application/xml; charset=utf-8";
                break;
            case "gif":
                contentType = "image/gif";
                break;
            case "jpg":
            case "jpeg":
                contentType = "image/jpeg";
                break;
            case "png":
                contentType = "image/png";
                break;
            case "zip":
                contentType = "application/zip";
                break;
            case "tar":
                contentType = "application/x-tar";
                break;
            case "gz":
                contentType = "application/gzip";
                break;
            case "mp3":
                contentType = "audio/mpeg";
                break;
            case "mp4":
                contentType = "video/mp4";
                break;
            case "md":
                contentType = "text/markdown";
                break;
            case "rp":
                contentType = "application/x-rp";
                break;
        }
        if (StringUtils.isNotBlank(contentType)) {
            return RetVal.success(contentType);
        }
        return RetVal.error("不支持该文件类型!");
    }
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java后端可以使用HttpClient库来实现Post提交文件流及参数的功能。示例代码如下: ```java CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(url); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); // 添加文件流 builder.addBinaryBody("file", file, ContentType.APPLICATION_OCTET_STREAM, fileName); // 添加参数 builder.addTextBody("param1", "value1", ContentType.TEXT_PLAIN); builder.addTextBody("param2", "value2", ContentType.TEXT_PLAIN); HttpEntity multipart = builder.build(); httpPost.setEntity(multipart); CloseableHttpResponse response = httpClient.execute(httpPost); ``` 其中,`url`是要提交到的服务端地址,`file`是要提交的文件流,`fileName`是文件名。`param1`和`param2`是要提交的参数及其对应的值。 在服务端接收文件流及参数,可以使用Spring框架的`MultipartFile`来接收文件流,使用`@RequestParam`来接收参数。示例代码如下: ```java @PostMapping("/upload") public String uploadFile(@RequestParam("file") MultipartFile file, @RequestParam("param1") String param1, @RequestParam("param2") String param2) throws IOException { byte[] bytes = file.getBytes(); // 处理文件流和参数 return "success"; } ``` 其中,`/upload`是服务端接收请求的地址,`file`是要接收的文件流,`param1`和`param2`是要接收的参数。 注意,在服务端接收参数,需要根据参数的类型来设置参数的`ContentType`。例如,如果参数是文本类型,则设置为`ContentType.TEXT_PLAIN`。如果参数是JSON类型,则设置为`ContentType.APPLICATION_JSON`。 以上就是Java后端HttpClient Post提交文件流及参数的实现方式。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值