MangoCool

springboot 提交表单和图片,后台对象接收

2018-09-21 10:53:12   作者:MangoCool   来源:MangoCool

简述:springboot项目中,前端表单提交数据,其中包括图片,后台以对象一并接收,然后直接入库,就这么简单的需求。

直接上代码:

CompanyInfoController 控制器:

package net.olym.symailp.website.controller;

import net.olym.symailp.core.util.AjaxUtils;
import net.olym.symailp.core.util.CommonResponseMap;
import net.olym.symailp.website.model.CompanyModel;
import net.olym.symailp.website.service.CompanyInfoService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/webmgr/companys")
public class CompanyInfoController {

    private static final Log LOG = LogFactory.getLog(CompanyInfoController.class);

    @Autowired
    HttpServletRequest request;

    @Autowired
    HttpServletResponse response;

    @Autowired
    CompanyInfoService companyInfoService;

    @RequestMapping(value="/info", method = RequestMethod.GET)
    public void getCompanyInfo() {

        CommonResponseMap dataMap = new CommonResponseMap();
        try {
            CommonResponseMap retMap = companyInfoService.getCompanyInfo();
            dataMap.putAll(retMap);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            dataMap.error();
        } finally {
            AjaxUtils.sendAjaxForObject(response, dataMap);
        }
    }

    @RequestMapping(value="/{id}", method = RequestMethod.POST)
    public void updateCompanyInfo(CompanyModel company) {

        CommonResponseMap dataMap = new CommonResponseMap();
        try {
            CommonResponseMap retMap = companyInfoService.updateCompanyInfo(company);
            dataMap.putAll(retMap);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            dataMap.error();
        } finally {
            AjaxUtils.sendAjaxForObject(response, dataMap);
        }
    }
}
CompanyInfoService 接口:
package net.olym.symailp.website.service;

import net.olym.symailp.core.util.CommonResponseMap;
import net.olym.symailp.website.model.CompanyModel;

public interface CompanyInfoService {

    CommonResponseMap getCompanyInfo() throws Exception;

    CommonResponseMap updateCompanyInfo(CompanyModel company) throws Exception;

}
CompanyInfoServiceImpl 实现类:
package net.olym.symailp.website.service;

import net.olym.symailp.core.util.CommonResponseMap;
import net.olym.symailp.core.util.FileUtil;
import net.olym.symailp.website.dao.CompanyInfoMapper;
import net.olym.symailp.website.model.CompanyModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

@Service("companyInfoService")
public class CompanyInfoServiceImpl implements CompanyInfoService {

    @Value("${server.uploadPath}")
    private String docPath;

    @Autowired
    CompanyInfoMapper companyInfoMapper;

    @Override
    public CommonResponseMap getCompanyInfo() throws Exception {

        CommonResponseMap dataMap = new CommonResponseMap();
        CompanyModel company = companyInfoMapper.getCompanyInfo();
        dataMap.success();
        dataMap.put("companyInfo", company==null?"":company);
        return dataMap;
    }

    @Override
    public CommonResponseMap updateCompanyInfo(CompanyModel company) throws Exception {

        CommonResponseMap dataMap = new CommonResponseMap();
        MultipartFile logoFile = company.getLogoFile();
        if(logoFile != null) {
            // 上传文件
            CommonResponseMap uploadMap = FileUtil.uploadFile(logoFile, docPath, "image");
            if(!"0".equals(uploadMap.get("code")+"")) {
                return uploadMap;
            } else {
                company.setLogo(uploadMap.get("fileUrl")+"");
            }
        }

        MultipartFile weiQrcodeFile = company.getWeiQrcodeFile();
        if(weiQrcodeFile != null) {
            // 上传文件
            CommonResponseMap uploadMap = FileUtil.uploadFile(weiQrcodeFile, docPath, "image");
            if(!"0".equals(uploadMap.get("code")+"")) {
                return uploadMap;
            } else {
                company.setWeiQrcode(uploadMap.get("fileUrl")+"");
            }
        }

        CompanyModel retCompany = companyInfoMapper.getCompanyInfo();
        if(retCompany == null) {
            companyInfoMapper.addCompanyInfo(company);
        } else {
            companyInfoMapper.updateCompanyInfo(company);
        }
        dataMap.success();
        return dataMap;
    }
}
CompanyInfoMapper dao接口:
package net.olym.symailp.website.dao;

import net.olym.symailp.website.model.CompanyModel;

import java.sql.SQLException;

public interface CompanyInfoMapper {

    CompanyModel getCompanyInfo() throws SQLException;

    int addCompanyInfo(CompanyModel company) throws SQLException;

    int updateCompanyInfo(CompanyModel company) throws SQLException;
}
CompanyInfoMapper.xml dao 映射文件 :
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="net.olym.symailp.website.dao.CompanyInfoMapper" >

    
    <select id="getCompanyInfo" resultType="net.olym.symailp.website.model.CompanyModel">
    select * from t_company_info limit 1;
    </select>

    <insert id="addCompanyInfo" parameterType="net.olym.symailp.website.model.CompanyModel">
        insert into t_company_info(company_name, address, full_address, telephone, postcode, fax, email, qq, icp, logo, wei_account, wei_qrcode, linkman, linkphone, profile)
        values(#{companyName,jdbcType=VARCHAR}, #{address,jdbcType=VARCHAR}, #{fullAddress,jdbcType=VARCHAR}, #{telephone,jdbcType=VARCHAR}, #{postcode,jdbcType=VARCHAR},
        #{fax,jdbcType=VARCHAR}, #{email,jdbcType=VARCHAR}, #{qq,jdbcType=VARCHAR}, #{icp,jdbcType=VARCHAR}, #{logo,jdbcType=VARCHAR},
        #{weiAccount,jdbcType=VARCHAR}, #{weiQrcode,jdbcType=VARCHAR}, #{linkman,jdbcType=VARCHAR}, #{linkphone,jdbcType=VARCHAR}, #{profile,jdbcType=VARCHAR});
    </insert>

    <update id="updateCompanyInfo" parameterType="net.olym.symailp.website.model.CompanyModel">
        update t_company_info
        set company_name=#{companyName}, address=#{address}, full_address=#{fullAddress}, telephone=#{telephone},
        postcode=#{postcode}, fax=#{fax}, email=#{email}, qq=#{qq},
        icp=#{icp}, logo=#{logo}, wei_account=#{weiAccount}, wei_qrcode=#{weiQrcode},
        linkman=#{linkman}, linkphone=#{linkphone}, profile=#{profile}
        where id=#{id};
    </update>

</mapper>
CompanyModel 模型:
package net.olym.symailp.website.model;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.multipart.MultipartFile;

public class CompanyModel {

    private long id;

    private String companyName;

    private String address;

    private String fullAddress;

    private String telephone;

    private String postcode;

    private String fax;

    private String email;

    private String qq;

    private String icp;

    private String logo;

    private MultipartFile logoFile;

    private String weiAccount;

    private String weiQrcode;

    private MultipartFile weiQrcodeFile;

    private String linkman;

    private String linkphone;

    private String profile;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getCompanyName() {
        return companyName;
    }

    public void setCompanyName(String companyName) {
        this.companyName = companyName;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getFullAddress() {
        return fullAddress;
    }

    public void setFullAddress(String fullAddress) {
        this.fullAddress = fullAddress;
    }

    public String getTelephone() {
        return telephone;
    }

    public void setTelephone(String telephone) {
        this.telephone = telephone;
    }

    public String getPostcode() {
        return postcode;
    }

    public void setPostcode(String postcode) {
        this.postcode = postcode;
    }

    public String getFax() {
        return fax;
    }

    public void setFax(String fax) {
        this.fax = fax;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getQq() {
        return qq;
    }

    public void setQq(String qq) {
        this.qq = qq;
    }

    public String getIcp() {
        return icp;
    }

    public void setIcp(String icp) {
        this.icp = icp;
    }

    public String getLogo() {
        return logo;
    }

    public void setLogo(String logo) {
        this.logo = logo;
    }

    public String getWeiAccount() {
        return weiAccount;
    }

    public void setWeiAccount(String weiAccount) {
        this.weiAccount = weiAccount;
    }

    public String getWeiQrcode() {
        return weiQrcode;
    }

    public void setWeiQrcode(String weiQrcode) {
        this.weiQrcode = weiQrcode;
    }

    public String getLinkman() {
        return linkman;
    }

    public void setLinkman(String linkman) {
        this.linkman = linkman;
    }

    public String getLinkphone() {
        return linkphone;
    }

    public void setLinkphone(String linkphone) {
        this.linkphone = linkphone;
    }

    public String getProfile() {
        return profile;
    }

    public void setProfile(String profile) {
        this.profile = profile;
    }

    public String toString() {
        JSONObject jsonObj = (JSONObject) JSON.toJSON(this);
        return jsonObj.toString();
    }

    public MultipartFile getLogoFile() {
        return logoFile;
    }

    public void setLogoFile(MultipartFile logoFile) {
        this.logoFile = logoFile;
    }

    public MultipartFile getWeiQrcodeFile() {
        return weiQrcodeFile;
    }

    public void setWeiQrcodeFile(MultipartFile weiQrcodeFile) {
        this.weiQrcodeFile = weiQrcodeFile;
    }

    public static void main(String[] args) {
        CompanyModel c = new CompanyModel();
        c.setAddress("daf");
        c.setFax("1");
        System.out.println(c);
    }
}
FileUtil 上传文件工具类:
package net.olym.symailp.core.util;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileUtil {

    //文件上传工具类服务方法
    public static CommonResponseMap uploadFile(MultipartFile file, String filePath, String fileType) throws Exception {

        CommonResponseMap dataMap = new CommonResponseMap();
        try {
            String fileName = "";
            String docUrl = "/document/" + fileName;
            if("document".equals(fileType)) {
                if(file == null) {
                    dataMap.fail(1, "上传文件不能为空");
                    return dataMap;
                }

                fileName = file.getOriginalFilename();
                String fileSuf = fileName.substring(fileName.lastIndexOf(".")+1);

                if(!"pdf".equals(fileSuf) && !"doc".equals(fileSuf) && !"docx".equals(fileSuf)) {
                    dataMap.fail(1, "文件类型只能是pdf,doc,docx");
                    return dataMap;
                }

                if(file.getSize() > 5242880) {
                    dataMap.fail(1, "文件大小不能超过5MB");
                    return dataMap;
                }
                docUrl = "/document/" + fileName;

            } else if("image".equals(fileType)) {

                fileName = file.getOriginalFilename();
                String fileSuf = fileName.substring(fileName.lastIndexOf(".")+1);

                if(!"png".equals(fileSuf) && !"jpg".equals(fileSuf) && !"jpeg".equals(fileSuf)) {
                    dataMap.fail(1, "文件类型只能是png,jpg,jpeg");
                    return dataMap;
                }

                if(file.getSize() > 5242880) {
                    dataMap.fail(1, "图片大小不能超过5MB");
                    return dataMap;
                }
                docUrl = "/company/" + fileName;
            }
            File targetFile = new File(filePath);
            if(!targetFile.exists()){
                targetFile.mkdirs();
            }
            FileOutputStream out = new FileOutputStream(filePath+fileName);
            out.write(file.getBytes());
            out.flush();
            out.close();
            dataMap.success();
            dataMap.put("fileUrl", docUrl);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            return dataMap;
        }
    }
}

前端提交测试用google插件 Postman:


期间调试时,前端表单提交,后台总是收不到数据,

这时错误的以为是后台对象接收数据这种方式,在提交的表单数据中不能包含 file,

原来是我错了,解决办法很简单,将表单提交方式改成 method = RequestMethod.POST 即可,我之前是 method = RequestMethod.PUT

这个坑算是我自己挖的了,想着restful的接口,update 应该用 PUT 方式提交了,这个不对。

标签: java springboot 表单提交 后台对象

分享:

上一篇springboot 上传文件超过限制,被全局异常处理捕获并返回,客户端收不到返回值

下一篇我只是为了打开Centos的8080端口而已

关于我

崇尚极简,热爱技术,喜欢唱歌,热衷旅行,爱好电子产品的一介码农。

座右铭

当你的才华还撑不起你的野心的时候,你就应该静下心来学习,永不止步!

人生之旅历途甚长,所争决不在一年半月,万不可因此着急失望,招精神之萎葸。

Copyright 2015- 芒果酷(mangocool.com) All rights reserved. 湘ICP备14019394号

免责声明:本网站部分文章转载其他媒体,意在为公众提供免费服务。如有信息侵犯了您的权益,可与本网站联系,本网站将尽快予以撤除。