使用xmlhttprequest将文件从javascript前端上载到java后端

ghg1uchk  于 2021-06-30  发布在  Java
关注(0)|答案(0)|浏览(266)

作为javascript(sapui5)和java后端应用程序的一部分,我实现了一个“contact us”表单,我希望用户能够将文件上传到这个表单并发送它。
然后我想把这些文件与表格中发送的信息一起发送给管理员电子邮件。我面临的问题是,我从javaapi得到了415错误响应,尽管我似乎正在设置发送的正确内容类型。
我现在的代码如下:javascript:

sendContactRequest: function(){
            var contactUsModel = this.getView().getModel("contactFormModel");
            var name = contactUsModel.getProperty("/name");
            var email = contactUsModel.getProperty("/email");
            var subject = contactUsModel.getProperty("/subject");
            var description = contactUsModel.getProperty("/description");
            var formData = new FormData();
            formData.append("file", contactUsModel.getProperty("/attachments")[0]);

            var url = formatter.getPrefixUrl("/Urisite/contactapi" + name + "/" + email + "/" + subject + "/" + description + "/1",this._oSitename);
            var xhr = new XMLHttpRequest();
            xhr.open('POST', url);
            xhr.setRequestHeader("Content-Type","multipart/form-data");
            xhr.setRequestHeader("x-csrf-token", this.csrfToken);

            xhr.send(formData);
            xhr.onreadystatechange = function(){
                if(xhr.readyState === 4){
                  var i = 8;
                }
            };
}

java 语:

@POST
    @Path("/{name}/{email}/{subject}/{description}/{attachmentCount}") 
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    public Response getNotificationByUser(@Context SecurityContext sc,
                                          @PathParam("name") String name,
                                          @PathParam("email") String email,
                                          @PathParam("subject") String subject,
                                          @PathParam("description") String description,
                                          @PathParam("attachmentCount") Integer attachmentCount,
                                          HttpServletRequest request,
                                          HttpServletResponse response) {
        try {
            List<InputStream> attachments = new ArrayList<>();
            if(attachmentCount > 0) {
                Part filePart = request.getPart("file");
                InputStream filecontent = filePart.getInputStream();
                attachments.add(filecontent);
            }
            EmailUtils.sendContactUsEmail(name, email, subject, description, attachments);

            Gson gson = new Gson();
            String json = gson.toJson("");
            return Response.ok().entity(json).build();
        }
        catch(Exception e) {
            return Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).build();
        }

    }

任何帮助都将不胜感激!

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题