Importar dependencias pom
<dependencia> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.4</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpmime</artifactId> <version>4.4</version> </dependency>
Subir código:
/** * * @param filepath 文件全路径 * @param fileName 文件名 * @return * @throws IOException */ @PostMapping(value = "/upfileload.do") public String upfileload(String filepath,String fileName) throws IOException { System.out.println("传入参数------》" + ruta del archivo + "----" + nombre del archivo); DataInputStream en = nulo; OutputStream fuera = nulo; HttpURLConnection conn = null; JSONObject resposeTxt = nulo; InputStream ins = nulo; ByteArrayOutputStream outStream = nulo; intentar { // URL url = nueva URL ("http://192.168.3.11:8081/mes-boot-doc/test/fileupload?fileName=shafei.xls"); URL url = nueva URL ("http://localhost:8009/fileupload?fileName="+fileName); conn = (HttpURLConnection) url.openConnection(); // 发送POST请求必须设置如下两行 conn.setDoOutput(true); conn.setUseCaches(falso); conn.setRequestMethod("POST"); conn.setRequestProperty("Tipo de contenido", "texto/html"); conn.setRequestProperty("Cache-Control", "no-cache"); conn.setRequestProperty("Charsert", "UTF-8"); con. conectar(); conn.setConnectTimeout(10000); salida = conexión.getOutputStream(); Archivo archivo = nuevo archivo (ruta de archivo); in = new DataInputStream(nuevo FileInputStream(archivo)); bytes enteros = 0; byte[] búfer = nuevo byte[1024]; while ((bytes = in.read(buffer)) != -1) { out.write(buffer, 0, bytes); } salida.flush(); // 返回流 if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) { ins = conn.getInputStream(); outStream = new ByteArrayOutputStream(); byte[] datos = nuevo byte[1024]; número int = -1; while ((cuenta = ins.read(datos, 0, 1024)) != -1) { } outStream.write(datos, 0, cuenta); } datos = nulo; resposeTxt = JSONObject.parseObject(nueva Cadena(outStream .toByteArray(), "UTF-8")); } } catch (Excepción e) { e.printStackTrace(); } finalmente { if (in != null) { in.close(); } if (salida!= nulo) { salida.cerrar(); } if (ins != null) { ins.close(); if (outStream != null) { outStream.close(); } if (conexión != null) { conexión.desconectar(); } } devuelve "ÉXITO"; }
Recibir código:
@PostMapping("/fileupload") public String uploadFile(solicitud HttpServletRequest, respuesta HttpServletResponse) arroja una excepción{ String fileName = request.getParameter("fileName"); System.out.println("nombre de archivo:"+nombre de archivo); String fileFullPath = "C:/HWKJ/FTP/" + fileName; InputStream entrada = nulo; FileOutputStream fos = nulo; intente { entrada = solicitud.getInputStream(); Archivo archivo = nuevo archivo ("C:/HWKJ/FTP/"); if(!archivo.existe()){ archivo.mkdirs(); } fos = new FileOutputStream(fileFullPath); tamaño int = 0; byte[] búfer = nuevo byte[1024]; while ((tamaño = input.read(buffer,0,1024)) ! fos.write(buffer, 0, size); } //Información de respuesta json string format Map<String,Object> responseMap = new HashMap<String,Object>(); responseMap.put("flag", true); / / Generar la respuesta json string String jsonResponse = JSONObject.toJSONString(responseMap); sendResponse(jsonResponse,response); } catch (IOException e) { //Información de respuesta json string format Map<String,Object> responseMap = new HashMap<String,Object>(); responseMap.put("flag", false); responseMap.put("errorMsg", e. getMessage ()); String jsonResponse = JSONObject.toJSONString(responseMap); enviarRespuesta(jsonRespuesta,respuesta); } finalmente{ if(input != null){ input.close(); } if(fos != nulo){ fos.close(); } } devuelve nulo; } /** * 返回响应 * * @throws Exception */ private void sendResponse(String responseString,HttpServletResponse respuesta) throws Exception { response.setContentType("application/json;charset=UTF-8"); PrintWriter pw = null; intente { pw = respuesta.getWriter(); pw.write(cadena de respuesta); pw.flush(); } finalmente { IOUtils.closeQuietly(pw); } }
prueba de cartero