SpringBoot 는 어떻게 서버 간 에 파일 을 업로드 하 는 예 시 를 우아 하 게 실현 합 니까?
                                            
 14031 단어  SpringBoot크로스 서버파일 업로드
                    
크로스 서비스 업로드 파일 설명도
 
 프로젝트 생 성
1.1 파일 업로드 항목
우선 아이디어 빠 른 구축 도구 로 springboot 프로젝트 를 만 듭 니 다.이름 은
fileupload이 고 파일 을 업로드 하 는 서버 입 니 다.spring 웹 모듈 을 선택 하면 됩 니 다.
 
 관련 매개 변수 설정
spring.servlet.multipart.enabled=true
spring.servlet.multipart.max-file-size=30MB
spring.servlet.multipart.max-request-size=30MB
#     url,    /    
file.upload.path=http://localhost:8888/fileuploadserver/uploads/크로스 서버 업로드 에 필요 한 jar 패키지 좌표
<dependency>
  <groupId>com.sun.jersey</groupId>
  <artifactId>jersey-core</artifactId>
  <version>1.18.1</version>
</dependency>
<dependency>
  <groupId>com.sun.jersey</groupId>
  <artifactId>jersey-client</artifactId>
  <version>1.18.1</version>
</dependency>jeex 프로젝트 를 만 듭 니 다.프로젝트 이름 은
fileuploadserver이 며 아무것도 설정 할 필요 가 없습니다.그리고 웹 앱 디 렉 터 리 아래 에uploads폴 더 를 만 들 고 위 항목 에 설 정 된 파일 과 주 소 를 계속 저장 한 다음 tomcat 환경 시작 을 설정 하면 됩 니 다.웹.xml 파일 의 설정 정 보 를 삭제 하 는 것 을 기억 하 세 요.아래 그림 과 같다.
 
  
  
 다른 항목 과 충돌 하지 않도록 Http 와 JMX 포트 를 바 꾸 세 요.
 
 2.서버 수신 파일 업로드 코드 작성
파일 업로드 와 처리 로 controller 클래스 를 만 듭 니 다.
업로드 한 파일 데 이 터 를 저장 하 는 데 사용 되 는 MultipartFile 클래스
package cn.jxj4869.fileupload.controller;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.UUID;
@Controller
public class FileController {
  @Value("${file.upload.path}")
  private String path;
  @RequestMapping("/fileupload/method1")
  @ResponseBody
  private String method1(@RequestParam("upload") MultipartFile upload) throws IOException {
    System.out.println("          ");
    String filename = upload.getOriginalFilename();
    //            ,uuid
    String uuid = UUID.randomUUID().toString().replace("-", "");
    filename = uuid + "_" + filename;
    //         
    Client client = Client.create();
    //           
    WebResource webResource = client.resource(path + filename);
    webResource.put(upload.getBytes());
    return "success";
  }
}목록 아래 에 놓다
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>fileupload</title>
</head>
<body>
<h3>method1</h3>
<form method="post" enctype="multipart/form-data" action="fileupload/method1">
  <input type="file" name="upload">
  <br>
  <input type="submit">
</form>
</body>
</html> 
  
  
  
 3.존재 하 는 문제점 과 해결 방법 을 분석한다.
3.1 문제 분석
위 에 적 힌 바 와 같이 우리 가 서버 주 소 를 연결 한 후에 바로
/resources/static/방법 으로 파일 을 올 릴 수 있다 는 것 은 매우 위험한 행위 임 에 틀림없다.업로드 과정 에서 사용자 검 사 를 하지 않 았 기 때문에 서버 가 그림 을 저장 하 는 경 로 를 알 고 정확 한 경 로 를 알 필요 가 없 으 며 서버 ip 주소 만 알 면 됩 니 다.그러면 그 는 put 방법 을 통 해 서버 에 무한 정 전송 할 수 있 습 니 다.apache 공식 이 2017 에 발표 한 구멍 에 따 르 면 put 방법 을 열 면 서버 에 파일 을 임의로 쓸 수 있 습 니 다.그러나
put방법 을 사용 하지 않 으 면put방법 이 필요 한 업무 가 사용 되 지 못 하 게 된다.하나의 해결 방법 은 tomcat 의 설정 을 수정 하 는 것 이다.tomcat 의/conf 디 렉 터 리 에 있 는
put을 수정 합 니 다.아래 부분 을 찾 으 세 요.web.xml을 true 로 설정 합 니 다.이렇게 하면 서버 에 파일 을 쓸 수 없습니다.
<servlet>
    <servlet-name>default</servlet-name>
    <servlet-class>org.apache.catalina.servlets.DefaultServlet</servlet-class>
    <init-param>
      <param-name>readonly</param-name>
      <param-value>true</param-value>
    </init-param>
  </servlet>readonly방법 으로 파일 을 쓰 는 것 을 금 지 했 기 때문이다.그렇다면 이 상황 은 어떻게 해 야 할 까?서버 에서 받 은 파일 업로드 요청 을 HttpPost 를 통 해 업로드 한 파일 정 보 를 파일 서버 에 보 내 는 아이디어 가 있 습 니 다.파일 서버 에서 저장 파일 을 받 을 지 여 부 를 스스로 처리 합 니 다.
 
 3.2 프로젝트 fileupload 설정 수정
HttpPost 관련 좌표 의존 추가
  <dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpclient</artifactId>
      <version>4.3.6</version>
    </dependency>
    <dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpmime</artifactId>
      <version>4.5</version>
    </dependency>
    <dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpcore</artifactId>
      <version>4.4.1</version>
    </dependency>application.properties
file.upload.path1=http://localhost:8888/fileupload/springboot 프로젝트 를 만 들 고**
put**프로젝트 와 같이 선택 하 십시오. 
 만 든 후
put디 렉 터 리 아래fileload폴 더 를 만 들 고 업로드 파일 의 위 치 를 저장 합 니 다.(실제 필요 에 따라 파일 저장 위 치 를 변경 할 수도 있 습 니 다)관련 매개 변수 설정
#                     ,          
file.upload.save-path=/uploads/
#      
file.upload.url=/uploads/**
server.port=8888
#      
spring.servlet.multipart.enabled=true
spring.servlet.multipart.max-file-size=30MB
spring.servlet.multipart.max-request-size=100MB배열 형식 으로
/resources/인 자 를 받 아 다 중 파일 업 로드 를 실현 합 니 다.업 로드 된 파일 을
uploads로 포장 한 후 HttpPost 로 파일 서버 에 보 냅 니 다.이곳 에 서 는 용법 을 좀 알 아야 한다.
package cn.jxj4869.fileupload.controller;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import org.apache.http.HttpEntity;
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.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.UUID;
@Controller
public class FileController {
  @Value("${file.upload.path1}")
  private String path1;
  @RequestMapping("/fileupload/method2")
  @ResponseBody
  private String method2(@RequestParam("upload") MultipartFile[] uploads) throws IOException {
    System.out.println("          ");
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(path1);
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    for (MultipartFile upload : uploads) {
      String filename = upload.getOriginalFilename();
      builder.addBinaryBody("upload", upload.getBytes(), ContentType.MULTIPART_FORM_DATA, filename);
    }
    try {
      HttpEntity entity = builder.build();
      httpPost.setEntity(entity);
      CloseableHttpResponse response = httpClient.execute(httpPost);
      System.out.println(response.getStatusLine().getStatusCode());
      String s = response.getEntity().toString();
      System.out.println(s);
    } catch (Exception e) {
    } finally {
      httpClient.close();
    }
    return "success";
  }
}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>fileupload</title>
</head>
<body>
<h3>method2</h3>
<form method="post" enctype="multipart/form-data" action="fileupload/method2">
  <input type="file" name="upload"><br><br>
  <input type="file" name="upload"><br><br>
  <input type="file" name="upload">
  <br><br>
  <input type="submit">
</form>
</body>
</html>받 은 컨트롤 러
MultipartFile현재 항목 이 있 는 경 로 를 가 져 옵 니 다.중국어 가 존재 하지 않 는 것 이 좋 습 니 다.오류 가 발생 할 수 있 습 니 다.
package cn.jxj4869.fileuploadserver1.controller;
import com.sun.javafx.scene.shape.PathUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
@Controller
public class FileController {
  @Value("${file.upload.save-path}")
  private String savePath;
  @PostMapping("/fileupload")
  @ResponseBody
  private String fileupload(HttpServletRequest request, @RequestParam("upload")MultipartFile[] uploads) throws IOException {
    System.out.println("    ");
    
    String path= ResourceUtils.getURL("classpath:").getPath()+savePath;
    File file = new File(path);
    if (!file.exists()) {
      file.mkdir();
    }
    for (MultipartFile upload : uploads) {
      String filename = upload.getOriginalFilename();
      String uuid = UUID.randomUUID().toString().replace("-", "");
      filename=uuid+"_"+filename;
      upload.transferTo(new File(path,filename));
    }
    return "success";
  }
}
package cn.jxj4869.fileuploadserver1.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cglib.core.WeakCacheKey;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class MySpringMvcConfig implements WebMvcConfigurer {
  @Value("${file.upload.save-path}")
  private String savePath;
  @Value("${file.upload.url}")
  private String url;
  @Override
  public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler(url).addResourceLocations("classpath:"+savePath);
  }
} 
  
  
 SpringBoot 가 어떻게 서버 간 업로드 파일 을 우아 하 게 실현 하 는 지 에 대한 예 시 를 소개 합 니 다.더 많은 SpringBoot 서버 간 업로드 파일 내용 은 우리 의 이전 글 을 검색 하거나 아래 의 관련 글 을 계속 조회 하 시기 바 랍 니 다.앞으로 많은 지원 바 랍 니 다!
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
【Java・SpringBoot・Thymeleaf】 에러 메세지를 구현(SpringBoot 어플리케이션 실천편 3)로그인하여 사용자 목록을 표시하는 응용 프로그램을 만들고, Spring에서의 개발에 대해 공부하겠습니다 🌟 마지막 데이터 바인딩에 계속 바인딩 실패 시 오류 메시지를 구현합니다. 마지막 기사🌟 src/main/res...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.