首先要在mysql服务器上创建一张表,表中存文件的字段用blob类型——二进制大文件
CREATE TABLE file(file_id SMALLINT UNSIGNED NOT NULL PRIMARY KEY,file MEDIUMBLOB NOT NULL);
客户端添加文件
VARIANT varBLOB; SAFEARRAY *psa; SAFEARRAYBOUND rgsabound[1]; if(pbyBuf)//要保存的数据都在buffer[]里 { rgsabound[0].lLbound = 0; rgsabound[0].cElements = dwFileLen; psa = SafeArrayCreate(VT_UI1, 1, rgsabound); ///创建SAFEARRAY对象 for (long i = 0; i < dwFileLen; i++) SafeArrayPutElement (psa, &i, &pbyBuf[i]); ///将buffer指向的二进制数据保存到SAFEARRAY对象psa中 varBLOB.vt = VT_ARRAY | VT_UI1; ///将varBLOB的类型设置为BYTE类型的数组 varBLOB.parray = psa; ///为varBLOB变量赋值 HRESULT hr; for ( DWORD dwItem = 10000; dwItem< 11000; dwItem++) { try { recordPtr->AddNew(); ///添加新记录 hr=recordPtr->Fields->GetItem("file")->AppendChunk(varBLOB);///加入BLOB类型的数据 //if(SUCCEEDED(hr)) } catch(_com_error &e) { AfxMessageBox(e.Description());
return ;
}
_variant_t tv;
tv.vt = VT_I4;
tv.lVal = dwItem;
recordPtr->PutCollect("fileid", tv);
//tv = recordPtr->Fields->GetItem("fileid")->Value;// = (UINT)1111;
try
{
recordPtr->Update();
}
catch(_com_error &e)
{
AfxMessageBox(e.Description());
return ;
}
}
//客户端读取代码:
_RecordsetPtr recordPtr;//数据集指针
recordPtr.CreateInstance("ADODB.Recordset");//(__uuidof(Recordset));
CString cmdStr=_T("select * from tabmirfile where fileid = 10000");//tabmirfile 为表名
try
{
recordPtr->Open(_variant_t(cmdStr),
conPtr.GetInterfacePtr(),
adOpenDynamic,
adLockOptimistic,
adCmdText);
}
catch (_com_error e)
{
AfxMessageBox(e.Description());
}
if (recordPtr->adoEOF || recordPtr->BOF)
{
int n = 0;
}
//read
_variant_t varBlobRead;
long lDataLen = recordPtr->GetFields()->GetItem("file")->ActualSize;
if (lDataLen > 0)
{
varBlobRead = recordPtr->GetFields()->GetItem("file")->GetChunk(lDataLen);
BYTE *pBuf = NULL;
BYTE *pBufTemp = NULL;
pBufTemp = (BYTE*)GlobalAlloc(GMEM_FIXED,lDataLen);
SafeArrayAccessData(varBlobRead.parray,(void **)&pBufTemp); pBuf = new BYTE[lDataLen]; memcpy(pBuf, pBufTemp, lDataLen); CFile outFile("d:\\aaaa.jpg",CFile::modeCreate|CFile::modeWrite|CFile::typeBinary); //构造新文件,如果文件存在,则长度变为0 outFile.Write(pBuf,lDataLen); outFile.Close(); delete []pBuf; SafeArrayUnaccessData (varBlobRead.parray); }
///
recordPtr->Close();//关闭记录集 recordPtr.Release();//释放空间