后台接收前端/客户端图片,并保存到数据库

图片从参数Map files中获取

package com.jsptpd.zhywserver.restcontrol;

import com.jsptpd.zhywserver.dao.IWorkOrderMapper;
import com.jsptpd.zhywserver.model.comman.FieldInfo;
import com.jsptpd.zhywserver.model.intallworkorder.OrderReturn;
import com.jsptpd.zhywserver.supportsystemservice.modelResult.pfservice.FinishWorkOrderParameter;
import com.jsptpd.zhywserver.supportsystemservice.modelResult.pfservice.PFCommonResult;
import com.jsptpd.zhywserver.util.FtpUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

/**
 * Created by HASEE on 2017/10/9.
 * 接收图片并保存到数据库
 */
public class dd {

    @Value("${pathconfig.ftpHost}")
    protected String ftpHost;
    @Value("${pathconfig.ftpPort}")
    protected int ftpPort = 21;
    @Value("${pathconfig.ftpUserName}")
    protected String ftpUserName;
    @Value("${pathconfig.ftpPassWord}")
    protected String ftpPassWord;
    @Value("${pathconfig.ftpOrderReturnPath}")
    protected String ftpOrderReturnPath;

    @Autowired
    protected IWorkOrderMapper workOrderMapper;

    /**
     * 回单接口, 包含回单的内容及回单的图片
     */
    @Override
    public boolean receiptOrder(Map files) throws Exception {

        //这里要图片上传
        for (Map.Entry file : files.entrySet()) {
            FtpUtil.uploadFile(ftpHost, ftpPort, ftpUserName, ftpPassWord, ftpOrderReturnPath,
                    "test", file.getKey(), file.getValue());

            //这里要图片的信息存入数据库
            workOrderMapper.insertPic(UUID.randomUUID().toString(), file.getKey(),
                    "ftp://" + ftpHost + ":" + ftpPort + ftpOrderReturnPath + "/" + "test" +
                            "/" + file.getKey(), "test", "用户签名", "装移拆回单");
        }

        PFCommonResult finisWorkOrder = pfServiceTest.getFinisWorkOrder();
//        PFCommonResult finisWorkOrder = pfService.getFinisWorkOrder(parameter);
        if ("回单成功".equals(finisWorkOrder.getStringReturn().getErrorDesc())) {
            return true;
        } else {
            log.info("失败原因 " + finisWorkOrder.getStringReturn().getErrorDesc());
            return true;
        }
    }
}

application.yml

server:
  port: 10002

#    interfaceUrl:
#      ipUrl: http://132.228.226.11
#    #  ftpUrl: http://132.228.226.11
#    #  ftpUrl: http://172.16.214.24
#      ftpUrl: http://172.16.108.137  # 本机的ip
#      oaUrl: http://nt.jsoa.net
#      vedioUrl: http://58.223.251.5:8080/axis2/services/GEForMsp

mybatis:
  configuration:
    mapUnderscoreToCamelCase: true

spring:
  resource: 
    static-locations: file:/public/
  http:
    multipart:
      max-file-size: 20Mb
      max-request-size: 80Mb
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: oracle.jdbc.driver.OracleDriver
#    公司内部数据库
    url: jdbc:oracle:thin:@172.16.241.177:1521:rjyorcl
    username: zhyw
    password: jsptpd123
#   内蒙电信数据库
#    url: jdbc:oracle:thin:@136.255.245.21:1521:orcl
#    username: zhyw
#    password: jsptpd
    initialSize: 5
    minIdle: 5
    maxActive: 20
    maxWait: 60000
    #自动检测关闭和空闲连接的间隔
    timeBetweenEvictionRunsMillis: 30000
    #最小生存时间
    minEvictableIdleTimeMillis: 300000
    validationQuery: SELECT 1 FROM DUAL
    testWhileIdle: true
    #这个参数设置为true,可以保证每次的连接都是正常的,但是。。 性能会降低, 建议使用空闲下检测30s一次, 这样服务器最多30s出现问题后恢复
    testOnBorrow: false
    testOnReturn: false
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=3000
    filters: stat
    #PSCatch
    poolPreparedStatements: true
    maxPoolPreparedStatementPerConnectionSize: 20
  datasource2:
#   统一装维库
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: oracle.jdbc.driver.OracleDriver
    url: jdbc:oracle:thin:@10.142.19.72:8022:tyzworcl
    username: tp_user
    password: Query#123
#    url: jdbc:oracle:thin:@172.16.241.177:1521:rjyorcl
#    username: zhab
#    password: zhab
    initialSize: 5
    minIdle: 5
    maxActive: 20
    maxWait: 60000
    #自动检测关闭和空闲连接的间隔
    timeBetweenEvictionRunsMillis: 30000
    #最小生存时间
    minEvictableIdleTimeMillis: 300000
    validationQuery: SELECT 1 FROM DUAL
    testWhileIdle: true
    #这个参数设置为true,可以保证每次的连接都是正常的,但是。。 性能会降低, 建议使用空闲下检测30s一次, 这样服务器最多30s出现问题后恢复
    testOnBorrow: false
    testOnReturn: false
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=3000
    filters: stat
    #PSCatch
    poolPreparedStatements: true
    maxPoolPreparedStatementPerConnectionSize: 20


destDirName: picture/
pathconfig:
  ftpHost: 172.16.241.145
  ftpPort: 9528
  ftpUserName: wanglong
  ftpPassWord: wanglong
  ftpOrderReturnPath: /images

# 标记是否用于测试
  isForTest: true

FtpUtil

public class FtpUtil {


    /**
     * Description: 向FTP服务器上传文件
     *
     * @param host     FTP服务器hostname
     * @param port     FTP服务器端口
     * @param username FTP登录账号
     * @param password FTP登录密码
     * @param basePath FTP服务器基础目录
     * @param filePath FTP服务器文件存放路径。例如分日期存放:/2015/01/01。文件的路径为basePath+filePath
     * @param filename 上传到FTP服务器上的文件名
     * @param input    输入流
     * @return 成功返回true,否则返回false
     */
    public static boolean uploadFile(String host, int port, String username, String password, String basePath,
                                     String filePath, String filename, InputStream input) {
        boolean result = false;
        FTPClient ftp = new FTPClient();
        try {
            int reply;

            ftp.connect(host, port);// 连接FTP服务器
            // 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器
            ftp.login(username, password);// 登录
            reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                return result;
            }
            //切换到上传目录
            if (!ftp.changeWorkingDirectory(basePath + filePath)) {
                //如果目录不存在创建目录
                String[] dirs = filePath.split("/");
                String tempPath = basePath;
                for (String dir : dirs) {
                    if (null == dir || "".equals(dir)) continue;
                    tempPath += "/" + dir;
                    if (!ftp.changeWorkingDirectory(tempPath)) {
                        if (!ftp.makeDirectory(tempPath)) {
                            return result;
                        } else {
                            ftp.changeWorkingDirectory(tempPath);
                        }
                    }
                }
            }
            //设置上传文件的类型为二进制类型
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
            //上传文件
            if (!ftp.storeFile(new String(filename.getBytes("GBK"),"iso-8859-1"), input)) {
                return result;
            }
            input.close();
            ftp.logout();
            result = true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ioe) {
                }
            }
        }
        return result;
    }

    /**
     * Description: 从FTP服务器下载文件
     *
     * @param host       FTP服务器hostname
     * @param port       FTP服务器端口
     * @param username   FTP登录账号
     * @param password   FTP登录密码
     * @param remotePath FTP服务器上的相对路径
     * @param fileName   要下载的文件名
     * @param localPath  下载后保存到本地的路径
     * @return
     */
    public static boolean downloadFile(String host, int port, String username, String password, String remotePath,
                                       String fileName, String localPath) {
        boolean result = false;
        FTPClient ftp = new FTPClient();
        try {
            int reply;
            ftp.connect(host, port);
            // 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器
            ftp.login(username, password);// 登录
            reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                return result;
            }
            ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录
            FTPFile[] fs = ftp.listFiles();
            for (FTPFile ff : fs) {
                if (ff.getName().equals(fileName)) {
                    File localFile = new File(localPath + "/" + ff.getName());

                    OutputStream is = new FileOutputStream(localFile);
                    ftp.retrieveFile(ff.getName(), is);
                    is.close();
                }
            }

            ftp.logout();
            result = true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ioe) {
                }
            }
        }
        return result;
    }
}

IWorkOrderMapper

@Mapper
public interface IWorkOrderMapper {
    //图片ID, 图片名称, 图片路径, 工单ID, 工单ID,  图片类型:装移拆回单, 修障回单什么的
    @Select("insert into APP_WORKORDER_PIC (  PIC_ID, PIC_NAME,PIC_PATH,ORDER_ID, WORK_ORDER_ID, PICTYPE) values " +
            "(  #{picId, jdbcType=VARCHAR}, #{picName, jdbcType=VARCHAR}, #{picPath, jdbcType=VARCHAR}, #{orderId, jdbcType=VARCHAR}, #{workOrderId, jdbcType=VARCHAR}, #{picType, jdbcType=VARCHAR})")
    void insertPic(@Param("picId") String picId, @Param("picName") String picName,
                   @Param("picPath") String picPath, @Param("orderId") String orderId,
                   @Param("workOrderId") String workOrderId, @Param("picType") String picType);
}

你可能感兴趣的:(后台接收前端/客户端图片,并保存到数据库)