2016-09-26 10 views
2

Я пытаюсь отправить файл на контроллер, используя его в FormBodyPart, вместо того, чтобы напрямую отправлять ему файл. Вот код для создания коллекции файловSpring org.springframework.web.multipart.support.MissingServletRequestPartException, Required request part 'file' нет

private void addFile(Collection<FormBodyPart> parts, File inputFile, String fileType) 
     throws ClassificationException { 
    if (inputFile == null) { 
     throw new ClassificationException("Null input file provided"); 
    } 
    if (!inputFile.exists()) { 
     throw new ClassificationException("Input file not found: " + inputFile.getAbsolutePath()); 
    } 
    if (fileType != null) { 

     String charset = "UTF-8"; 
     parts.add(new FormBodyPart("file", new FileBody(inputFile, fileType, charset))); 

    } else { 
     parts.add(new FormBodyPart("file", new FileBody(inputFile, inputFile.getName()))); 
    } 
} 

Сбор деталей - это аррайалист, в который будут входить файлы.

Вот мой код для установки Http Entity

HttpPost httppost = new HttpPost("http://localhost:9000/upload1"); 
      MultipartEntity reqEntity1 = new MultipartEntity(); 
      FormBodyPart part1; 
      for (Iterator i$ = parts.iterator(); i$.hasNext(); reqEntity1.addPart(part1)) { 
       part1 = (FormBodyPart) i$.next(); 
       System.out.println(part1.getHeader()); 
      } 

      httppost.setEntity(reqEntity1); 
      HttpResponse response = httpclient.execute(httppost); 
      System.out.println(response); 

Мой метод декларирование контроллера

String index(@RequestParam("file") MultipartFile uploadfile)

Я получаю сообщение об ошибке с сервера о том

[ 400] {«timestamp»: 1474898550131, «status»: 400, «error»: «Bad Request», «exception»: «o rg.springframework.web.multipart.support.MissingServletRequestPartException», "сообщение": "файл "Обязательная часть запроса нет", "пути": "/ upload1"}

Моего dispatcher.xml уже содержит bean of multipartResolver.

Я довольно новичок в веб-сервисах и, возможно, делаю какую-то глупую ошибку. Пожалуйста, помогите мне, спасибо заранее

+0

Вы не должны использовать '$' в именах переменных. [Спецификация языка Java §3.8] (https://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-3.8): * Знак '$' должен использоваться только в механически сгенерированный исходный код или, реже, для доступа к уже существующим именам в устаревших системах. * – Andreas

+0

Вы уверены, что 'parts' не пуст? – Andreas

+0

Когда я печатаю детали, он показывает «[[email protected]]», поэтому я не думаю, что он пуст. –

ответ

1
verify if you have this items: 
@Bean 
public CommonsMultipartResolver multipartResolver() { 
CommonsMultipartResolver multipart = new CommonsMultipartResolver(); 
multipart.setMaxUploadSize(3 * 1024 * 1024); 
return multipart;} 

@Bean 
@Order(0) 
public MultipartFilter multipartFilter() { 
MultipartFilter multipartFilter = new MultipartFilter(); 
multipartFilter.setMultipartResolverBeanName("multipartResolver"); 
return multipartFilter; 
} 


and in the pplications.properties 


# MULTIPART (MultipartProperties) 
spring.http.multipart.enabled=true 
# Enable support of multi-part uploads. 
# spring.http.multipart.file-size-threshold=3 # Threshold after which files will be written to disk. Values can use the suffixed "MB" or "KB" to indicate a Megabyte or Kilobyte size. 
spring.http.multipart.location=/
# Intermediate location of uploaded files. 
spring.http.multipart.max-file-size=10MB 
# Max file size. Values can use the suffixed "MB" or "KB" to indicate a Megabyte or Kilobyte size. 
spring.http.multipart.max-request-size=10MB 
# Max request size. Values can use the suffixed "MB" or "KB" to indicate a Megabyte or Kilobyte size. 
spring.http.multipart.resolve-lazily=false 
# Whether to resolve the multipart request lazily at the time of file or parameter access. 
+0

Спасибо @pablo! Application.properties действительно помогает мне в течение нескольких дней поиска ... – Hongliang