415不支持的媒体类型

时间:2014-08-15 08:04:07

标签: java spring http spring-mvc file-upload

我有一个带文件上传的表单,有时候我正在捕获415 unsupported media type而日志中没有消息。这是我的表格:

<form:form method="post" enctype="multipart/form-data"
    class="form-horizontal" modelAttribute="massSMSForm"
    style="width: 650px;">

    <c:if test="${!empty errorFlag}">
        <div class="alert alert-danger">
            <a href="#" class="close" data-dismiss="alert">&times;</a> <b>Ошибка.
            </b>
            <form:errors path="*" />

        </div>
    </c:if>
    <div class="well" style="width: 650px;">

        <table style="width: 100%">

            <tr>
                <td align="left"><b>Наименование рассылки*</b></td>
                <td align="right"><form:input path="title" type="text"
                        class="form-control" id="title" style="width:340px;"
                        maxlength="15" /><br /></td>
            <tr>
                <td align="left"><b>Отправитель*</b></td>
                <td align="right"><form:input path="from" type="text"
                        maxlength="15" class="form-control" id="from" style="width:340px;" /><br /></td>
            </tr>
            <tr>
                <td align="left"><b>Дата начала рассылки</b></td>
                <td align="right"><form:input id="deliveryDate"
                        path="deliveryDate" type="text" autocomplete="off"
                        class="form-control" placeholder="сейчас" style="width:310px;" /><br /></td>
            </tr>
            <tr>
                <td align="left"><b>Срок жизни</b></td>
                <td align="right"><form:input id="expiration" path="expiration"
                        type="number" min="1" max="72" autocomplete="off"
                        class="form-control" placeholder="в часах" style="width:310px;" /><br /></td>
            </tr>
            <tr>
                <td align="left"><b>Файл рассылки*</b></td>
                <td align="right"><input type="file" name="file"
                    accept="text/xml, text/plain" id="mass" /><br /></td>
            </tr>

        </table>


        <br /> <b>Текст сообщения рассылки</b><br /> <br />
        <c:choose>
            <c:when test="${massSMSForm.ignore==false}">
                <form:textarea path="message" class="form-control" rows="5"
                    id="message" placeholder="..." maxlength="500" />

            </c:when>

            <c:otherwise>
                <form:textarea path="message" class="form-control" rows="5"
                    id="message" placeholder="..." disabled="true" maxlength="500" />

            </c:otherwise>
        </c:choose>




        <br />
        <form:checkbox path="ignore" id="ignoreBox" />
        <small>Игнорировать сообщение</small>


    </div>



    <div style="text-align: right">
        <a href="/${initParam['appName']}/userRole/"
            class="btn btn-link btn-sm">Назад</a><input
            class="btn btn-success btn-sm" type="submit" name="send"
            onclick="myAlert()" value="Отправить" />
    </div>


</form:form>


<script type="text/javascript">
    function confirmSend() {
        if (confirm("Отправляем сообщения?")) {
            return true;
        } else {
            return false;
        }
    }
</script>

<script type="text/javascript">
    jQuery('#deliveryDate')
            .datetimepicker(
                    {
                        lang : 'ru',
                        i18n : {
                            ru : {
                                months : [ 'Январь', 'Февраль', 'Март',
                                        'Апрель', 'Май', 'Июнь', 'Июль',
                                        'Август', 'Сентябрь', 'Октябрь',
                                        'Ноябрь', 'Декабрь', ],
                                dayOfWeek : [ "Вс", "Пн", "Вт", "Ср", "Чт",
                                        "Пт", "Сб", ]

                            }
                        },
                        dayOfWeekStart : 1,
                        timepicker : true,
                        format : 'Y-m-d H:i'
                    });
</script>

<script type="text/javascript">
    document.getElementById('ignoreBox').onchange = function() {
        document.getElementById('message').disabled = this.checked;
    };
</script>

方法:

@RequestMapping(value = "/sms/mass", method = RequestMethod.POST, headers = "content-type=multipart/form-data")
public String massSMSProcess(Map<String, Object> map,
        @ModelAttribute("massSMSForm") MassSMSForm massSMSForm,
        BindingResult result, HttpSession session) throws IOException {

    session.removeAttribute(SESSION_KEY);

    massSMSFormValidator.validate(massSMSForm, result);

    if (result.hasErrors()) {
        map.put("errorFlag", true);
        return massSMSPage(map, massSMSForm, session);
    } else {
        try {
            SMS sms = SmsBuilder.build(massSMSForm);
            session.setAttribute(SESSION_KEY, sms);
            map.put("title", "Подтверждение операции");
            map.put("count", sms.getSmsEntityList().size());
        } catch (IOException e) {
            // mailer.send("/sms/mass :" + e.getMessage() + "form:"
            // + massSMSForm);

            map.put("error", "Ошибка ввода/вывода");
            return distributionListPage(map);
        }
        return "confirmMassSMSPage";
    }
}

有什么问题?是js问题还是什么?我应该添加新标头吗?你有什么想法?

4 个答案:

答案 0 :(得分:4)

无需在@RequestMapping中设置标头。默认情况下,Formenctype="multipart/form-data"的发布请求被视为Controller中的多部分请求。 所以这里你的请求已经是multipart,你只需要为文件上传添加一些maven存储库来支持你的multipart-data

参考this Spring file upload documentation并浏览this example

答案 1 :(得分:2)

尝试改变:

headers = "content-type=multipart/form-data"

到:

consumes="multipart/form-data"

所以你的@RequestMapping会变成这样:

@RequestMapping(value = "/sms/mass",
                method = RequestMethod.POST, 
                consumes="multipart/form-data")

答案 2 :(得分:2)

如果您还没有这样做,请尝试在应用程序上下文中添加multipartResolver bean。在application / servlet context xml文件中添加它。

<bean id="multipartResolver"
    class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

    <!-- one of the properties available; the maximum file size in bytes -->
    <property name="maxUploadSize" value="100000"/>

</bean>

支持jar文件commons-fileupload jar。这个jar的Maven依赖是:

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

答案 3 :(得分:2)

尝试将异常处理程序添加到控制器。它将帮助您确定问题的真正原因:

@ExceptionHandler({Exception.class})
public void resolveException(Exception e) {
    e.printStackTrace();
}