0

我正在尝试使用 apache commons 上传图像,但在与我的实体绑定时出现异常。

表单对象

<sf:form action="${contextPath}client/saveClient" modelAttribute="client" method="POST"
                 enctype="multipart/form-data"> 
            <label>Add Logo</label><input type="file"  name='logo' /><br/>
        </sf:form>

控制器

 @RequestMapping("/saveClient")
    public ModelAndView addClient(@RequestParam("logo") MultipartFile file, HttpSession request,
            @Valid Client client, BindingResult result, Model model) throws IOException {

        ModelAndView mvc = new ModelAndView();
        if (result.hasErrors()) {
            mvc.addObject("client", client);
            mvc.setViewName(MANAGECLIENT_PREFIX + "addclient");
            return mvc;
        } else {
            clientService.uploadImage(file, request);
            clientRepository.add(client);
            model.addAttribute("client", client);
            mvc.setViewName(MANAGECLIENT_PREFIX + "saveclient");
            return mvc;
        }
    }

服务

public void uploadImage(MultipartFile file, HttpSession request) throws IOException {
    logger.info("Enter upload client logo");
    Utilities utilities = new Utilities();
    if (!file.isEmpty()) {
        String fileName = (utilities.getUniqueId() + file.getOriginalFilename());
        System.out.println("Image name: {" + fileName + "}");
        String contextPath = request.getServletContext().getRealPath("/");
        String filePath = contextPath + "\\WEB-INF\\clientlogo\\" + fileName;
        String validFileFormat = utilities.validFileFormat(fileName);
        if (!validFileFormat.isEmpty()) {
            BufferedImage src = ImageIO.read(new ByteArrayInputStream(file.getBytes()));
            File destination = new File(filePath);
            ImageIO.write(src, validFileFormat, destination);
            client.setLogo(fileName);
        }
    }
}

实体

@Column(name = "logo")
private String logo;

例外

Field error in object 'client' on field 'logo': rejected value [org.springframework.web.multipart.commons.CommonsMultipa
rtFile@58d51629]; codes [typeMismatch.client.logo,typeMismatch.logo,typeMismatch.java.lang.String,typeMismatch]; argumen
ts [org.springframework.context.support.DefaultMessageSourceResolvable: codes [client.logo,logo]; arguments []; default
message [logo]]; default message [Failed to convert property value of type 'org.springframework.web.multipart.commons.Co
mmonsMultipartFile' to required type 'java.lang.String' for property 'logo'; nested exception is java.lang.IllegalStateE
xception: Cannot convert value of type [org.springframework.web.multipart.commons.CommonsMultipartFile] to required type
 [java.lang.String] for property 'logo': no matching editors or conversion strategy found]}]

我正在尝试将图像名称存储在数据库中,并将图像存储在应用程序目录中。我应该如何解决这种类型转换。

4

3 回答 3

0

这只是一个绑定错误 - 您的对象“客户端”具有不同类型的“徽标”属性。您可以忽略该特定错误。

利用:

if (result.hasErrors() && (result.getErrorCount()>1 || !result.hasFieldError("logo")) {
 ....
} 

含义:只有在出现超过 1 个错误(“logo”字段上总是有错误)或者您遇到的单个错误不是“logo”错误时,您才应该对错误做出反应。

于 2013-03-13T09:57:42.597 回答
0

The exception says

Cannot convert value of type [org.springframework.web.multipart.commons.CommonsMultipartFile] to required type [java.lang.String] for property 'logo': no matching editors or conversion strategy found]}]

Cause You have defined @RequestParam("logo") on MultipartFile parameter

于 2013-02-25T16:44:04.827 回答
0

第 1 步:在表单标签中添加 enctype="multipart/form-data" 属性。

步骤2:注册一个MultipartResolver bean,并在配置文件/类中返回CommonsMultipartResolver,并确保bean名称必须为“multipartResolver”,默认情况下Spring使用方法名称作为bean名称。

第 3 步:创建数据库连接对象并将其注入 DAO 类。

第四步:使用注入的数据库连接使用JdbcTemplate查询数据库。

第 5 步:最后创建一个处理用户请求的控制器类。

 @Configuration
    @EnableWebMvc
    @ComponentScan(basePackages = { "org.websparrow.controller", "org.websparrow.dao" })
    public class WebMvcConfig {

        @Bean
        public InternalResourceViewResolver viewResolver() {

            InternalResourceViewResolver vr = new InternalResourceViewResolver();
            vr.setPrefix("/");
            vr.setSuffix(".jsp");

            return vr;
        }

        @Bean
        public MultipartResolver multipartResolver() {
            return new CommonsMultipartResolver();
        }

        @Bean
        public DriverManagerDataSource getDataSource() {

            DriverManagerDataSource ds = new DriverManagerDataSource();
            ds.setDriverClassName("com.mysql.jdbc.Driver");
            ds.setUrl("jdbc:mysql://localhost:3306/yourdatabase");
            ds.setUsername("root");
            ds.setPassword("");

            return ds;
        }

        @Bean
        public ImageDao getConnectionObject() {
            return new ImageDao(getDataSource());
        }
    }
    public class ImageDao {

        private JdbcTemplate jdbcTemplate;

        public ImageDao(DataSource dataSource) {
            jdbcTemplate = new JdbcTemplate(dataSource);
        }

        public int inserRecords(String name, Integer age, MultipartFile photo) throws IOException {

            byte[] photoBytes = photo.getBytes();

            String sql = "INSERT INTO STUDENT(NAME,AGE,PHOTO) VALUES (?,?,?)";

            return jdbcTemplate.update(sql, new Object[] { name, age, photoBytes });
        }
    }

    @Controller
    public class ImageController {

        @Autowired
        ImageDao imageDao;

        @RequestMapping(value = "/InsertImage", method = RequestMethod.POST)
        public ModelAndView save(@RequestParam("name") String name, @RequestParam("age") Integer age,
                @RequestParam("photo") MultipartFile photo) {

            try {
                imageDao.inserRecords(name, age, photo);

                return new ModelAndView("index", "msg", "Records succesfully inserted into database.");

            } catch (Exception e) {
                return new ModelAndView("index", "msg", "Error: " + e.getMessage());
            }
        }
    }
//Database
    CREATE TABLE `student` (
      `id` int(5) NOT NULL AUTO_INCREMENT,
      `name` varchar(30) DEFAULT NULL,
      `age` int(3) DEFAULT NULL,
      `photo` mediumblob,
      PRIMARY KEY (`id`)
    );**strong text**
//html form
<form action="InsertImage" method="post" enctype="multipart/form-data">

<pre>

    Name: <input type="text" name="name">

    Age: <input type="number" name="age">

    Photo: <input type="file" name="photo">

    <input type="submit" value="Submit">

</pre>

</form>
于 2019-03-31T04:35:15.220 回答