不啰嗦,直接上代码
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; } }