Struts2+Hibernate realizes image upload to database

JSP page section

In order to upload pictures, we need to set the upload picture part as a form.
The specific code is as follows:

<s:form action="UploadPicture" enctype="multipart/form-data">
        <s:file name="image" label="选择照片"/>
        <s:submit value="上传"/>
</s:form>

<s:file/> is the element of this form, which is used to upload files.
It should be noted that we need to set the form encoding format (ie the enctype attribute) to multipart/form-data to indicate that the data uploaded by the form is binary data.

struts.xml section

In order to realize the function of identifying whether the file is a picture and controlling the size of the picture, we need to define an interceptor for the action: fileUpload interceptor. To achieve the above function, we need to set two parameters for this interceptor: maximumSize and allowedTypes, the former is used to Limits the size of the file, which is used to identify the file's format. The value of the parameter maximumSize is in bytes, for example, 1MB is written as 1048576, and the value of allowedType is the image format, separated by commas.

<action name="UploadPicture" class="com.demo.UploadProfilePicture">
        <interceptor-ref name="defaultStack" />
        <interceptor-ref name="fileUpload" >
            <param name="maximumSize">1048576</param>
            <param name="allowedTypes">
                image/bmp,image/jpg,image/png,image/gif,image/jpeg
            </param>
        </interceptor-ref>
        <!--下面正常配置result,此处省略-->
</action>

Action section

Look at the following code, which indicates several key places:
HibernateUtil tool class reference: https://blog.csdn.net/vipmao/article/details/51340525
The data type of the column corresponding to the database storage image is required to be Blob type

public class UploadPicture extends ActionSupport
{
    private static final long serialVersionUID = 1L;

    //该表单的元素,类型为File,需要设置setter、getter方法(关键点一)
    private File image;

    public String execute()
    {
        HttpServletRequest request = ServletActionContext.getRequest();
        HttpSession session = request.getSession();

        Session hibernateSession = HibernateUtil.currentSession();
        Transaction tx = hibernateSession.beginTransaction();

        try 
        {
            //将该图片转为二进制输入流(关键点二)
            FileInputStream fis = new FileInputStream(getImage());
            //设置一个byte数组,数组长度为该图片的字节数目(关键点三)
            byte[] content = new byte[fis.available()];
            //二进制流输入到数组(关键点四)
            fis.read(content);
            //备注:User类是一个映射数据库表的类
            User user = (User)session.getAttribute("user");
            //设置该图片数组到这个对象的属性,该属性类型同样是byte[]类型(关键点四)
            user.setPicture(content);
            //更新数据库
            hibernateSession.update(user);
            tx.commit();
            HibernateUtil.closeSession();
            request.setAttribute("sysMsg", "上传成功");

            return SUCCESS;
        }
        //如果上传的文件不符合要求会被拦截器拦截,并抛出NullPointerException异常
        catch(NullPointerException e)
        {
            tx.rollback();
            request.setAttribute("sysMsg", "上传失败:文件过大或图片格式不符合要求");
            HibernateUtil.closeSession();
            return ERROR;
        }
        catch (Exception e)
        {
            e.printStackTrace();
            tx.rollback();
            HibernateUtil.closeSession();
            request.setAttribute("sysMsg", "服务器异常");
            return ERROR;
        }
    }

    public File getImage() {
        return image;
    }

    public void setImage(File image) {
        this.image = image;
    }
}

If you want to know how to read the pictures in the database to the front page, you can refer to my blog:
https://blog.csdn.net/abc123lzf/article/details/79780079

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326064185&siteId=291194637