Error 415 - File Upload

0

pom.xml

      <dependency>
          <groupId>commons-fileupload</groupId>
          <artifactId>commons-fileupload</artifactId>
          <version>1.3.3</version>
      </dependency>

Angular, save method

  getSalvar(arquivo : Arquivo, selectedFile: File) {
    let arquivoImportar = JSON.stringify(
      { 
        'files' : selectedFile,
        'idEntidade' : arquivo.entidade,
        'idEmpresa' : arquivo.empresa
      }
    );
    return this.http.post(this.userUrl + "/salvar", arquivoImportar, this.options)
      .map((response: Response) => {
        console.log("Salvar arquivos importados " + response.status);
       return response.json();
      }).catch((error:any) => 
        Observable.throw(error.json().error || 'Erro em salvar arquivos importados ' + console.log(this.options))
      );
  }

Java method

@RestController
@RequestMapping(value = "/admin")
public class ArquivoImportadoController {

    @CrossOrigin(origins = "*")
        @PostMapping(value = "/arquivoImportadoRecurso/salvar", produces = MediaType.APPLICATION_JSON_UTF8_VALUE, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
        public RetornoJackson gravarBanco(
                @RequestParam("files") MultipartFile files,
                @RequestParam("idEntidade") Long idEntidade,
                @RequestParam("idEmpresa") Long idEmpresa) {
            RetornoJackson retorno = new RetornoJackson();
            ArquivoImportadoEntity arquivoImportacao = new ArquivoImportadoEntity();
            try {
                ArquivosEntity arquivo = new ArquivosEntity();
                ArquivoArquivoEntity arquivoArquivo = new ArquivoArquivoEntity();
                arquivo(files, arquivo);
                arquivoImportacao(files, idEntidade, idEmpresa, arquivoImportacao,
                        arquivoArquivo);
                arquivoArquivo(arquivoImportacao, arquivo, arquivoArquivo);
                arquivoImportadoServico.validarCampos(arquivoImportacao);
                Set<ArquivoArquivoEntity> arquivosArquivos = new LinkedHashSet<ArquivoArquivoEntity>();
                arquivosArquivos.add(arquivoArquivo);
                arquivo.setArquivosArquivos(arquivosArquivos);
                arquivoImportacao.setArquivosArquivos(arquivosArquivos);
                arquivoImportadoServico.salvar(arquivoImportacao);
                retorno.setTipo(TipoRetornoMensagemEnum.SUCESSO);
                retorno.setMensagem(Constantes.SALVA_SUCESSO);
            } catch (RegraNegocioException e) {
                logger.error(Constantes.erroSalvar(arquivoImportacao.getClass()
                        .getName()), e);
                retorno.setTipo(TipoRetornoMensagemEnum.ERRO);
                retorno.setMensagem(e.getMessage());
            } catch (Exception e) {
                logger.error(Constantes.erroSalvar(arquivoImportacao.getClass()
                        .getName()), e);
                retorno.setTipo(TipoRetornoMensagemEnum.ERRO);
                retorno.setMensagem(e.getMessage());
            }
            return retorno;
        }
}

Browser console error.

zone.js:2935 POST http://localhost:8080/des-if-web/admin/arquivoImportadoRecurso/salvar 415 (Unsupported Media Type)
scheduleTask @ zone.js:2935
ZoneDelegate.scheduleTask @ zone.js:407
onScheduleTask @ zone.js:297
ZoneDelegate.scheduleTask @ zone.js:401
Zone.scheduleTask @ zone.js:232
Zone.scheduleMacroTask @ zone.js:255
scheduleMacroTaskWithCurrentZone @ zone.js:1092
(anonymous) @ zone.js:2967
proto.(anonymous function) @ zone.js:1372
(anonymous) @ http.js:1640
Observable._trySubscribe @ Observable.js:172
Observable.subscribe @ Observable.js:160
MapOperator.call @ map.js:57
Observable.subscribe @ Observable.js:157
CatchOperator.call @ catchError.js:80
Observable.subscribe @ Observable.js:157
MapOperator.call @ map.js:57
Observable.subscribe @ Observable.js:157
ArquivoFormComponent.onSubmit @ arquivo-form.component.ts:80
(anonymous) @ ArquivoFormComponent.html:1
handleEvent @ core.js:13547
callWithDebugContext @ core.js:15056
debugHandleEvent @ core.js:14643
dispatchEvent @ core.js:9962
(anonymous) @ core.js:12301
schedulerFn @ core.js:4343
SafeSubscriber.__tryOrUnsub @ Subscriber.js:243
SafeSubscriber.next @ Subscriber.js:190
Subscriber._next @ Subscriber.js:131
Subscriber.next @ Subscriber.js:95
Subject.next @ Subject.js:56
EventEmitter.emit @ core.js:4311
NgForm.onSubmit @ forms.js:5762
(anonymous) @ ArquivoFormComponent.html:1
handleEvent @ core.js:13547
callWithDebugContext @ core.js:15056
debugHandleEvent @ core.js:14643
dispatchEvent @ core.js:9962
(anonymous) @ core.js:10587
(anonymous) @ platform-browser.js:2628
ZoneDelegate.invokeTask @ zone.js:421
onInvokeTask @ core.js:4740
ZoneDelegate.invokeTask @ zone.js:420
Zone.runTask @ zone.js:188
ZoneTask.invokeTask @ zone.js:496
invokeTask @ zone.js:1517
globalZoneAwareCallback @ zone.js:1543
:4200/#/arquivo/novo:1 Failed to load http://localhost:8080/des-if-web/admin/arquivoImportadoRecurso/salvar: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 415.

As picture 1, I understand that the file is arriving in the save method.

Image 1

Aspicture2,thefilesarenotbeingpopulatedtosendtotheserver.

Picture2

I'm wondering if this is happening, because as I understand it, before sending it to the server, the files are empty.

What can it be?

    
asked by anonymous 08.04.2018 / 23:28

1 answer

0

I have modified the way to send to the server, thus:

 constructor(
        private httpClient: HttpClient,
        private http: Http,
        private authenticationService: AuthenticationService
      ) {}

    salvarArquivo(files: File, arquivo : Arquivo): Observable<HttpEvent<{}>> {
        let formdata: FormData = new FormData();
        formdata.append('files', files);
        formdata.append('idEntidade', String(arquivo.entidade));
        formdata.append('idEmpresa', String(arquivo.empresa));
        const req = new HttpRequest('POST',  this.userUrl + "/salvar", formdata, {
          reportProgress: true,
          responseType: 'text'
        });
        return this.httpClient.request(req);
      }

But I did not understand, what's the difference between being sent by HttpClient and Http ?

    
11.04.2018 / 12:19