2017-05-23 81 views
0

我需要將照片上傳到使用Spring Boot編寫的服務器。對於發送請求的前端,我使用Angular2。使用Angular2發送MultipartFile作爲請求參數給REST服務器

這是我接受HTTP請求的API。它工作正常。 (我用郵差測試過)

@RequestMapping(method = RequestMethod.POST, value = "/tender/save-new/save-photo") 
public ResponseEntity<?> uploadPhoto(@RequestParam("file") MultipartFile file){ 

    if (file.isEmpty()) { 
     ErrorResponse errorResponse = new ErrorResponse(); 
     errorResponse.setMessage("DEBUG: Attached file is empty"); 
     return new ResponseEntity<ErrorResponse>(errorResponse, HttpStatus.NOT_FOUND); 
    } 
    String returnPath = null; 
    try { 
     // upload stuff 
    } catch (IOException e) { 
     ErrorResponse errorResponse = new ErrorResponse(); 
     errorResponse.setMessage(e.getMessage()); 
     return new ResponseEntity<ErrorResponse> (errorResponse, HttpStatus.INTERNAL_SERVER_ERROR); 
    } 

    return new ResponseEntity<String>(returnPath, HttpStatus.OK); 
} 

我不知道該如何在Angular2中編寫代碼來調用服務器。 以下是我想出的。

savePhoto(photoToSave: File) { 

    let formData: FormData = new FormData(); 
    formData.append('file', photoToSave); 

    let savedPath = this._http 
     .post(this._endpointUrl + "tender/save-new/save-photo", formData) 
     .map(
     res => { 
      return res.json(); 
     } 
     ) 
     .catch(handleError); 

    return savedPath; 
} 

正如你所看到的,我在發送之前追加'file'參數表單數據。服務器方法接受RequestParam作爲'file'

但是,在服務器日誌中,我收到以下錯誤。

org.springframework.web.multipart.MultipartException:當前請求 不在 org.springframework.web.method.annotation.RequestParamMethodArgumentResolver.handleMissingValue(RequestParamMethodArgumentResolver.java:190)多部分請求

請注意,由於SprinBoot隱式處理它,因此我沒有聲明CommonsMultipartResolver bean。 (我聽說過,如果我錯了,請糾正)

我認爲由於請求中缺少值而出現錯誤。春天在說什麼handleMissingValue?我錯過了什麼?

回答

0

你需要指定你的控制器期待多

@RequestMapping(method = RequestMethod.POST, value = "/tender/save-new/save-photo", consumes = {"multipart/form-data"}) 
public ResponseEntity<?> uploadPhoto(@RequestParam("file") MultipartFile file){ 

也是解決您需要添加您計劃在您的CORS映射使用方法CORS問題,嘗試這樣的事情

@Configuration 
public class WebMvcConfiguration { 

@Bean 
public WebMvcConfigurer corsConfigurer() { 
    return new WebMvcConfigurerAdapter() { 
     @Override 
     public void addCorsMappings(CorsRegistry registry) { 
      registry.addMapping("/**").allowedMethods("GET", "POST", "PUT", "DELETE", "HEAD"); 
     } 
    }; 
} 
} 
+0

但根據以下的答案,Angular2最終支持文件上傳,而不XHR https://stackoverflow.com/a/39862337/3892439 – vigamage

+0

嗯這很有意思。 ,不知道它是否受支持,您是否在解決方案的第二部分中將消耗= {「multipart/form-data」}放入您的請求映射中? –

+0

是的。現在它給了我「否」Access-Control-Allow-Origin'標題出現在請求的資源上。原因'http:// localhost:3000'因此不被允許訪問。 ''。但事情是我已經把'@CrossOrigin(origins =「http:// localhost:3000」)'在我的控制器 – vigamage

0

我有同樣的問題,這就是我使用的是現在的解決方案:

使用彈簧啓動後端:

0使用Angular
@RequestMapping(value="/save", method = RequestMethod.POST) 
public ResponseEntity<?> saveTemp(@RequestParam("file") MultipartFile file) throws Exception{ 
    String nomFichier=file.getOriginalFilename(); 

    try { 
     byte[] bytes = file.getBytes(); 
     File fi=new File(tempRepo+nomFichier); 
     fi.getParentFile().mkdirs(); 
     BufferedOutputStream bufferedOutputStream = new BufferedOutputStream((new FileOutputStream(fi))); 
     bufferedOutputStream.write(bytes); 
     bufferedOutputStream.close(); 



    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
     return new ResponseEntity<>(HttpStatus.BAD_REQUEST); 
    } 
    return new ResponseEntity<>(HttpStatus.OK); 
} 

爲前端:

public save(file:any){ 

const formData = new FormData(); 
formData.append("file", file); 

return this._http 
    .post('http://localhost:8081/save', formData) 
    .catch(this._errorhandler); 
} 
+0

你是否將特定http請求的標頭設置爲某個或某些東西? – vigamage

+0

不,我不設置請求的標題,它會自動完成 –

相關問題