java 上传文件 多个文件 单个文件 上传图片,上传PDF,上传doc文档等各种文件方式,附上代码

不啰嗦,直接上代码


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @NAME: hzan
 * @DATE: 2022/11/17
 *  文件上传
 **/
@Slf4j
public class import {

    /**
     * 文件上传
     * ModelAndView 响应 可以自己定义响应类型
     * @param req
     * @param res
     * @return
     * @throws Exception
     */
    public ModelAndView importFile(HttpServletRequest req, HttpServletResponse res) throws Exception {
        try {
            log.info("图片上传开始");
            //上传存放文件的路径
            String imageUploadPath="url";
            log.info("图片上传地址:"+imageUploadPath);

            JSONObject jj = new JSONObject();
            MultipartHttpServletRequest multiPartReq = (MultipartHttpServletRequest) req;
            MultipartFile tfile = null;
            //前段传的特殊标识自行判断
            String type = req.getParameter("type");
            if(StringUtils.isNotBlank(type)) {
                tfile = multiPartReq.getFile(req.getParameter("type"));
            }else {
                tfile = multiPartReq.getFile("file");
            }
            //获取文件名
            String filename = tfile.getOriginalFilename();
            String reg = ".+(docx|DOCX|DOC|doc|PDF|pdf|JPEG|jpeg|JPG|jpg|GIF|gif|BMP|bmp|PNG|png)$";
            Pattern pattern = Pattern.compile(reg);
            Matcher matcher = pattern.matcher(filename);
            //设置响应状态
            rendText(res);
            //1024*1024=1MB 比较文件大小,和文件格式
            if(tfile.getSize() > 1024*1024 && matcher.find()) {
                jj.put("result", "err");
                jj.put("message", "文件过大");
            }else {
                FilePathVO file = uploadFile(tfile, imageUploadPath);
                if(file != null && StringUtils.isNotBlank(file.getVisitUrl()) ) {
                    jj.put("data", file);
                    jj.put("result", "success");
                    jj.put("message", "上传成功");
                }else {
                    jj.put("result", "error");
                    jj.put("message", "上传失败");
                }
            }

            res.getWriter().print(jj.toJSONString());
            res.getWriter().close();

            log.info("文件上传结束");
            return null;
        }catch (Exception e) {
            log.error("图片上传异常:"+e.getMessage());
            e.printStackTrace();
        }
        return null;

    }

    private void rendText(HttpServletResponse res) {
        res.setContentType("text/plain");
        res.setCharacterEncoding("UTF-8");
        res.setHeader("Pragma", "no-cache");
        res.setHeader("Cache-Control", "no-cache, must-revalidate");
        res.setHeader("Pragma", "no-cache");
    }

    /**
     * 上传单个图片/文件
     *
     * @param upload
     * @param path   服务地址
     * @return
     * @throws IOException
     */
    public static FilePathVO uploadFile(MultipartFile upload, String path) throws IOException {
        FilePathVO filePathDTO = null;

        String content = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(path);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();



        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(15000).setConnectionRequestTimeout(11000)
                .setSocketTimeout(15000).build();
        httpPost.setConfig(requestConfig);

        if (upload != null && upload.getInputStream() != null && org.apache.commons.lang3.StringUtils.isNotEmpty(upload.getOriginalFilename())) {

            String filename = upload.getOriginalFilename();
            builder.addBinaryBody("file", upload.getBytes(), ContentType.MULTIPART_FORM_DATA, filename);

            try {
                HttpEntity entity = builder.build();
                httpPost.setEntity(entity);
                CloseableHttpResponse response = httpClient.execute(httpPost);

                InputStream in = response.getEntity().getContent();

                content = IOUtils.toString(in, "utf-8");
//                System.out.println(content);
//                System.out.println(response.getStatusLine().getStatusCode());

                if (200==response.getStatusLine().getStatusCode()) {
                    filePathDTO = JSON.parseObject(content, FilePathVO.class);
                } else {
                    return null;
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                httpClient.close();
            }
        }
        return filePathDTO;
    }

    /**
     * 上传多个文件
     *
     * @param uploads
     * @param path    服务地址
     * @return
     * @throws IOException
     */
    public static FileListVO uploadFiles(MultipartFile uploads[], String path) throws IOException {
        FileListVO fileListVO = new FileListVO();
        String content = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(path);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        if (uploads != null && uploads.length > 0) {
            for (int i = 0; i < uploads.length; i++) {
                if (uploads[i] != null && uploads[i].getInputStream() != null && org.apache.commons.lang3.StringUtils.isNotEmpty(uploads[i].getOriginalFilename())) {
                    String filename = uploads[i].getOriginalFilename();
                    builder.addBinaryBody("files", uploads[i].getBytes(), ContentType.MULTIPART_FORM_DATA, filename);
                }
            }
        }

        try {
            HttpEntity entity = builder.build();
            httpPost.setEntity(entity);
            CloseableHttpResponse response = httpClient.execute(httpPost);
            InputStream in = response.getEntity().getContent();

            content = IOUtils.toString(in, "utf-8");

            if ("200".equals(response.getStatusLine())) {
                fileListVO = (FileListVO) JSON.parseObject(content, FileListVO.class);
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            httpClient.close();
        }
        return fileListVO;
    }
}

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值