从服务器上面根据url下载附件然后存到数据库中去

从服务器上面根据url下载附件然后存到数据库中去

写在前面,首先咱们要做下载附件存到数据库中需要的几个步骤

  1. 根据url下载附件
  2. 把下载的附件转化为2进制
  3. 把二进制作为大字段存到数据库指定表的指定字段中去

ok,现在咱们了解到需要怎样的步骤了,接下开就去具体看看怎么做

根据url下载附件

还是一样,咱们先想一下下载附件需要的几个步骤

  1. 确定自己的url地址
  2. 用输入输出流来获取自己的附件
  3. 确定一下要下载到的目录
    确定了怎么做,下面咱们上代码,注释我写的很清楚了,我就不多解释了
/**
     * 根据Url下载url中的附件
     * @param urlStr
     * @param fileName
     * @param savePath
     * @throws IOException
     */
    public static void  downLoadFromUrl(String urlStr,String fileName,String savePath) throws IOException{
   	    //确定自己的url地址
        URL url = new URL(urlStr);  
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();  //连接
        //设置超时间为3秒
        conn.setConnectTimeout(3*1000);
        //防止屏蔽程序抓取而返回403错误
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0;Windows NT; DigExt)");
        //得到输入流
        InputStream inputStream = conn.getInputStream();  
        //获取自己数组(方法在下面)
        byte[] getData = readInputStream(inputStream);    
        //文件保存位置(文件下载后的位置)
        File saveDir = new File(savePath);
        if(!saveDir.exists()){
            saveDir.mkdir();
        }
        File file = new File(saveDir+File.separator+fileName);    
        FileOutputStream fos = new FileOutputStream(file);     
        fos.write(getData); 
        if(fos!=null){
            fos.close();  
        }
        if(inputStream!=null){
            inputStream.close();
        }
		//打印一下,顺便作为文件成功下载的标记
        System.out.println("info:"+url+" download success"); 
    }



    /**
     * 从输入流中获取字节数组
     * @param inputStream
     * @return
     * @throws IOException
     */
    public static  byte[] readInputStream(InputStream inputStream) throws IOException {  
        byte[] buffer = new byte[1024];  
        int len = 0;  
        ByteArrayOutputStream bos = new ByteArrayOutputStream();  
        while((len = inputStream.read(buffer)) != -1) {  
            bos.write(buffer, 0, len);  
        }  
        bos.close();  
        return bos.toByteArray();  
    }  
	 /**
     * main方法测试
     * @String args
     */
    public static void main(String[] args) {
        try{
		//这个地址你们是访问不到,因为网络限制,测试的话放自己可以访问的地址哦
       downLoadFromUrl("http://101.95.48.97:8005/res/upload/interface/apptutorials/manualstypeico/6f83ce8f-0da5-49b3-bac8-fd5fc67d2725.png",  "百度.jpg","d:/resource/images/diaodiao/country/");
        }catch (Exception e) {
            // TODO: handle exception
        }
    }

把下载的附件转化为二进制记录到数据库中去

(2,3步骤放一块写了)步骤

  1. 附件路径
  2. 字节流转换
  3. 记录到数据库中
    话不多说直接上代码
public void pdf() throws Exception{
try {
//实体自定义
XxfbJcjb xxfbJcjb = new XxfbJcjb();
File file = new File("C:\\Users\Administrator\Desktopl\pdf\\系统使用说明.pdf");
//字节流转换赋值
xfbJcjb.setJbnr(getBytesFromFile(file));
//插库操作具体方法不在赘述
xxfbJcjbMapper . insertSelective(xxfbJcjb);
//String Jbnr=getBytesFromFile(file);
} catch (Exception e) {
LogUtil error(getClass(), ”操作出错",e);
	}
}

public static byte[] getBytesFromFile(File f ){
if (f = nul1){
return nul1;
}
try{
//开通文件输入输出流
FileInputStream stream = new FileInputStream(f);
ByteArrayutputstreom out = new
ByteArrayOutputstrean();
byte[] b = nen byte[1000];
int n;
while ((n = stream.read(b) != -1){
out.write(b,0,n);
}
stream.close();
out.close;
//转换后的二进制数据
return out.toByteArray();
}catch(IOException e){

}
return null ;
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java 可以使用 JavaMail API 实现将邮件拉取到数据库并保存附件至本地。具体实现大致流程如下: 1. 使用 JavaMail API 连接邮箱服务器,获取邮件信息。 2. 解析邮件,获取邮件中的附件。 3. 将邮件存入数据库中,并返回该邮件在数据库中的 ID。 4. 将附件按照邮件 ID 和附件名保存至本地。 示例代码如下(需要替换成对应的邮箱地址、用户名、密码、数据库信息): ``` // 连接邮箱服务器 String host = "smtp.gmail.com"; String username = "your_email_address"; String password = "your_email_password"; Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", host); props.put("mail.smtp.port", "587"); Session session = Session.getInstance(props, new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); // 获取邮件信息 Store store = session.getStore("imaps"); store.connect(host, username, password); Folder inbox = store.getFolder("INBOX"); inbox.open(Folder.READ_ONLY); Message[] messages = inbox.getMessages(); // 处理邮件 Connection conn = DriverManager.getConnection(DB_URL, DB_USERNAME, DB_PASSWORD); PreparedStatement stmt = conn.prepareStatement("INSERT INTO emails (subject, content) VALUES (?, ?)", Statement.RETURN_GENERATED_KEYS); for (Message message : messages) { // 保存邮件 stmt.setString(1, message.getSubject()); stmt.setString(2, message.getContent().toString()); stmt.executeUpdate(); ResultSet rs = stmt.getGeneratedKeys(); rs.next(); int emailId = rs.getInt(1); // 保存附件 Multipart multipart = (Multipart) message.getContent(); for (int i = 0; i < multipart.getCount(); i++) { BodyPart bodyPart = multipart.getBodyPart(i); if (Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition())) { String fileName = bodyPart.getFileName(); InputStream is = bodyPart.getInputStream(); // 保存附件 FileOutputStream fos = new FileOutputStream("path/to/attachments/" + emailId + "_" + fileName); byte[] buf = new byte[4096]; int bytesRead; while ((bytesRead = is.read(buf)) != -1) { fos.write(buf, 0, bytesRead); } fos.close(); is.close(); } } } conn.close(); // 关闭连接 inbox.close(false); store.close(); ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值