如何使用resteasy在angular中正确发送文件?

时间:2018-11-12 12:06:24

标签: angular rest file resteasy

我在angular 5应用中拥有当前服务:

Mahara Invalid Login      
${all_rows}=    Get All Rows    ${invalid_login_file}    ${DELIMITER}    ${HEADER}
:FOR    ${row}    IN    @{all_rows} 
\    ${login}=    Set Variable    ${row[0]}
\    ${password}=    Set Variable    ${row[1]}
\    Invalid ${login} with ${password}

我在Java应用程序中有resteasy方法:

const httpOptions = {
  headers: new HttpHeaders({ 'Accept': 'application/json', 'Content-Type': 'multipart/form-data' })
};

@Injectable()
export class UploadService {

  constructor(private http: HttpClient) { }

  // file from event.target.files[0]
  uploadFile(url: string, file: File): Observable<any> {

    let formData = new FormData();    
    formData.append('upload', file, file.name);                
    return this.http.post(url, formData, httpOptions);        
  }
}

问题是我需要知道服务器端的文件名,至少是文件名后缀,即文件的类型。例如,如果有人上传jpeg,我想保存jpeg而不是png作为默认值。 是否有更好的方法从“ multipart / form-data”发送文件,如果是,在这种情况下服务器端方法的定义是什么? 谢谢!

1 个答案:

答案 0 :(得分:0)

我结束了下载两个jar文件:

  1. resteasy-multipart-provider-1.1-RC2.jar
  2. mail-1.4.jar

然后,我在uploadPhotomethod(其余服务)中使用了MultipartFormDataInput,看看更新后的方法:

@POST
    @Path("Company/Logo/{companyId}")
    @Consumes("multipart/form-data")
    @Produces("application/json")
    public Response  uploadPhoto(MultipartFormDataInput input){

        String fileName = "";       
        Map<String, InputPart> uploadForm = input.getFormData();
        InputPart inputPart = uploadForm.get("upload");
         try {

            MultivaluedMap<String, String> header = inputPart.getHeaders();
            fileName = getFileName(header);

            //convert the uploaded file to inputstream
            InputStream inputStream = inputPart.getBody(InputStream.class,null);

            byte [] bytes = IOUtils.toByteArray(inputStream);               
            //constructs upload file path           
            writeFile(bytes,fileName);                      

          } catch (IOException e) {
            e.printStackTrace();
          }

        return Response.status(200)
            .entity("uploadFile is called, Uploaded file name : " + fileName).build();
    }

并且有角度的请求标头看起来像这样(已删除“ Content-Type”:“ multipart / form-data”)。

const httpOptions = {
  headers: new HttpHeaders({ 'Accept': 'application/json' })
};

我希望这对其他人有帮助!