Error 415 - Upload files

Asked

Viewed 88 times

0

pom.xml

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

Angular, method of saving

  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;
        }
}

Error in browser console.

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 image 1, understand that the file is coming in the save method.

Image 1 inserir a descrição da imagem aqui

According to image 2, the files are not being filled out to send to the server.

Image 2 inserir a descrição da imagem aqui

I’m finding strange this is occurring, because from what I understand, before sending to the server, the files is empty.

What can it be ?

1 answer

0

I was able to modify the way to send to the server, so:

 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 don’t understand, what’s the difference between being sent by Httpclient and by Http ?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.