Spring MVC 和 Blueimp jQuery 文件上传错误 406

Error 406 with Spring MVC and Blueimp jQuery File Upload

我正在使用 Blueimp jQuery File Upload + Spring MVC, and i have followed this example 构建我的应用程序。

它有一个多文件上传来上传图片。 图片已成功上传,但服务器return出现错误406。

我已经看到问题是我的控制器方法或应用程序配置的 return 类型,但我无法修复它。

jQuery 文件上传使用 AJAX 上传文件,可能是 AJAX 导致了问题?

这是我的控制器:

@Controller
public class UploadController {

    private static final Logger logger = LoggerFactory
            .getLogger(UploadController.class);

    @Autowired
    private ImagenManager imagenManager;

    private String fileUploadDirectory = "C:\Users\user\Desktop\";

    @RequestMapping(value = "/uploadImagen.htm", method = RequestMethod.GET, headers="Accept=application/json")
    public @ResponseBody Map listImagen() {
        logger.debug("uploadGet called");
        List<Imagen> list = imagenManager.getImagenList();
        for (Imagen image : list) {
            image.setUrl("/picture/" + image.getId());
            image.setThumbnailUrl("/thumbnail/" + image.getId());
            image.setDeleteUrl("/delete/" + image.getId());
            image.setDeleteType("DELETE");
        }
        Map<String, Object> files = new HashMap<String, Object>();
        files.put("files", list);
        logger.debug("Returning: {}", files);
        return files;
    }

    @RequestMapping(value = "/uploadImagen.htm", method = RequestMethod.POST, headers="Accept=application/json")
    public @ResponseBody Map upload(MultipartHttpServletRequest request, HttpServletResponse response) {
        logger.debug("uploadPost called");
        Iterator<String> itr = request.getFileNames();
        MultipartFile mpf;
        List<Imagen> list = new LinkedList<Imagen>();

        while (itr.hasNext()) {
            mpf = request.getFile(itr.next());
            logger.debug("Uploading {}", mpf.getOriginalFilename());

            String newFilenameBase = UUID.randomUUID().toString();
            String originalFileExtension = mpf.getOriginalFilename().substring(mpf.getOriginalFilename().lastIndexOf("."));
            String newFilename = newFilenameBase + originalFileExtension;
            String storageDirectory = fileUploadDirectory;
            String contentType = mpf.getContentType();

            File newFile = new File(storageDirectory + "/" + newFilename);
            try {
                mpf.transferTo(newFile);

                BufferedImage thumbnail = Scalr.resize(ImageIO.read(newFile), 290);
                String thumbnailFilename = newFilenameBase + "-thumbnail.png";
                File thumbnailFile = new File(storageDirectory + "/" + thumbnailFilename);
                ImageIO.write(thumbnail, "png", thumbnailFile);

                Imagen image = new Imagen();
                image.setName(mpf.getOriginalFilename());
                image.setThumbnailName(thumbnailFilename);
                image.setNewFilename(newFilename);
                image.setContentType(contentType);
                image.setSize(mpf.getSize());
                image.setThumbnailSize(thumbnailFile.length());
                image = imagenManager.crear(image);

                image.setUrl("/picture/" + image.getId());
                image.setThumbnailUrl("/thumbnail/" + image.getId());
                image.setDeleteUrl("/delete/" + image.getId());
                image.setDeleteType("DELETE");

                list.add(image);

            } catch (IOException e) {
                logger.error("Could not upload file " + mpf.getOriginalFilename(), e);
            }

        }

        Map<String, Object> files = new HashMap<String, Object>();
        files.put("files", list);
        return files;
    }

    @RequestMapping(value = "/picture/{id}", method = RequestMethod.GET)
    public void picture(HttpServletResponse response, @PathVariable int id) {
        Imagen image = imagenManager.get(id);
        File imageFile = new File(fileUploadDirectory + "/" + image.getNewFilename());
        response.setContentType(image.getContentType());
        response.setContentLength((int) image.getSize());
        try {
            InputStream is = new FileInputStream(imageFile);
            IOUtils.copy(is, response.getOutputStream());
        } catch (IOException e) {
            logger.error("Could not show picture " + id, e);
        }
    }

    @RequestMapping(value = "/thumbnail/{id}", method = RequestMethod.GET)
    public void thumbnail(HttpServletResponse response, @PathVariable int id) {
        Imagen image = imagenManager.get(id);
        File imageFile = new File(fileUploadDirectory + "/" + image.getNewFilename());
        response.setContentType(image.getContentType());
        response.setContentLength((int) image.getThumbnailSize());
        try {
            InputStream is = new FileInputStream(imageFile);
            IOUtils.copy(is, response.getOutputStream());
        } catch (IOException e) {
            logger.error("Could not show thumbnail " + id, e);
        }
    }

    @RequestMapping(value = "/delete/{id}", method = RequestMethod.DELETE)
    public @ResponseBody List delete(@PathVariable int id) {
        Imagen image = imagenManager.get(id);
        File imageFile = new File(fileUploadDirectory + "/" + image.getNewFilename());
        imageFile.delete();
        File thumbnailFile = new File(fileUploadDirectory + "/" + image.getThumbnailName());
        thumbnailFile.delete();
        imagenManager.delete(image);
        List<Map<String, Object>> results = new ArrayList<Map<String, Object>>();
        Map<String, Object> success = new HashMap<String, Object>();
        success.put("success", true);
        results.add(success);
        return results;
    }
}

我的应用-config.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd">

    <bean id="messageSource"
          class="org.springframework.context.support.ResourceBundleMessageSource">
        <property name="basename" value="messages" />
    </bean>

    <!-- Scans the classpath of this application for @Components to deploy as
        beans -->
    <context:component-scan base-package="com.pintia.pintiaserver.web" />

    <!-- Configures the @Controller programming model -->
    <mvc:annotation-driven>
        <mvc:message-converters>
            <bean class="org.springframework.http.converter.StringHttpMessageConverter"/>
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
        </mvc:message-converters>
    </mvc:annotation-driven>

    <!-- Handles HTTP GET requests for /resources/** by efficiently serving
        up static resources in the ${webappRoot}/resources directory -->
    <mvc:resources mapping="/resources/**" location="/resources/" />

    <bean id="viewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass"
                  value="org.springframework.web.servlet.view.JstlView"></property>
        <property name="prefix" value="/WEB-INF/views/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

    <bean id="multipartResolver"
          class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- max upload size in bytes -->
        <property name="maxUploadSize" value="20971520" /> <!-- 20MB -->

        <!-- max size of file in memory (in bytes) -->
        <property name="maxInMemorySize" value="1048576" /> <!-- 1MB -->

    </bean>

</beans>

如有任何帮助,我将不胜感激。

提前致谢。

正如 Luke Woodward 在 中解释的那样,将 /uploadImagen.htm 替换为 /uploadImagen,错误 406 消失了。