上传文件到服务器端的问题,回复有分 用swt写的客户端如何能上传文件到服务器端呢?能不能在服务器端用servlet写个fileupload,然后在客户端调用?怎么调用?求些思路 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 在swt通过io 直接上传到服务器某个文件夹目录下面,应该可以把要不就模拟http请求,去请求某个servlet,对servlet写你的文件流! 这是一个思路,你swt写的程序应该通过sockt与服务器通信的吧,如果你要用servlet,应该是要模拟HTTP请求的。 你可能要研究研究java的jnlp了 可不可以用socket啊,取得socket的输入,输出流,然后直接操作输入,输出流。 客户端是swt的桌面应用程序吗?是就可以使用SOCKET把文件传到服务器上,web的话可以考虑模拟http client上传 可以在服务器端写struts2有专门的上传组件,你可以去查下,很好用 swt 没用过 帮不了 jnlp是通过浏览器执行java应用程序啊,和我这个方向相反吧 用数据流方式上传文件到服务器 //以下为保存文件,视情况修改 String file = getFile1(); System.out.print(file); System.out.print(getfileFileName()); if(null!=file); { FileOutputStream outputStream = new FileOutputStream("上传服务器目录" + "文件名"); FileInputStream fileIn = new FileInputStream(file); byte[] buffer = new byte[1024]; int len; while ((len = fileIn.read(buffer)) > 0); { outputStream.write(buffer, 0, len);; } fileIn.close();; outputStream.close();; } CSDN有很多资源的可以去看看我里面也有一个 要看你服务器端是什么,也是SWT的话用Socket就可以了。如果是WebApp的话你就模拟一个Http上传文件的请求。 查一查HttpURLConnection机器父类URLConnection的相关API方法;做一个类似HTTPClient的东东;能解决这样的问题;我做过VC和Servlet通信的东西,原理上差不多,就是模拟Http请求;你可以参考一下;CString MakeRequestHeaders( CString& strBoundary ){ CString strFormat; CString strData; strFormat = _T( "Content-Type: multipart/form-data; boundary=%s\r\n" ); strData.Format( strFormat, strBoundary ); return strData;}CString MakePreFileData( CString& strBoundary, CString& strFileName ){ CString strFormat; CString strData; strFormat += _T( "--%s" ); strFormat += _T( "\r\n" ); strFormat += _T( "Content-Disposition: form-data; name=\"file\"; filename=\"%s\"" ); strFormat += _T( "\r\n" ); strFormat += _T( "Content-Type: application/x-www-form-urlencoded" ); strFormat += _T( "\r\n\r\n"); strData.Format( strFormat, strBoundary, strFileName ); return strData;}int GetPreDateLenth ( CString& strBoundary ){ CString strFormat; CString strData; strFormat += _T( "--%s" ); strFormat += _T( "\r\n" ); strFormat += _T( "Content-Disposition: form-data; name=\"file\"; filename=\"\"" ); strFormat += _T( "\r\n" ); strFormat += _T( "Content-Type: application/x-www-form-urlencoded" ); strFormat += _T( "\r\n\r\n"); strData.Format( strFormat, strBoundary ); return strData.GetLength();}CString MakePostFileData( CString& strBoundary ){ CString strFormat; CString strData; strFormat = _T( "--%s--" ); strData.Format( strFormat, strBoundary ); return strData;}long CWISH_FileTransferCtrl::UploadFile(LPCTSTR httpHost, short httpPort, LPCTSTR httpUrl, LPCTSTR filePath) { // TODO: Add your dispatch handler code here long lFileSize = 0; try { CString host = httpHost; INTERNET_PORT nPort = httpPort; CString url = httpUrl; url.Replace('\\','/'); CString local = filePath; local.Replace('/','\\'); CInternetSession session; CHttpConnection *pHttpConnection = NULL; CHttpFile* pHttpFile; CString strHTTPBoundary; CString strPreFileData; CString strPostFileData; DWORD dwTotalRequestLength; DWORD dwChunkLength; DWORD dwReadLength; DWORD dwResponseLength; void* pBuffer; LPSTR szResponse; CString strResponse; DWORD tmpLength = 0; DWORD curLength = 0; CFile localFile; if(FALSE == localFile.Open(local, CFile::modeRead | CFile::shareDenyNone)) { FireOnError("本地文件\"" + local + "\"无法打开!"); return -1; } lFileSize = localFile.GetLength(); strHTTPBoundary = newGUID(); strPreFileData = MakePreFileData(strHTTPBoundary, local); strPostFileData = _T("\r\n") + MakePostFileData(strHTTPBoundary); dwTotalRequestLength = strPreFileData.GetLength() + lFileSize + strPostFileData.GetLength(); dwChunkLength = 64 * 1024; pBuffer = malloc( dwChunkLength ); if (NULL == pBuffer) { localFile.Close(); FireOnError("组件申请内存空间失败!"); return -1; } pHttpConnection = session.GetHttpConnection( host, nPort ); pHttpFile = pHttpConnection->OpenRequest( CHttpConnection::HTTP_VERB_POST, url ); pHttpFile->AddRequestHeaders( MakeRequestHeaders( strHTTPBoundary ) ); try { pHttpFile->SendRequestEx( dwTotalRequestLength, HSR_SYNC | HSR_INITIATE ); FireOnUploadProgress(0); tmpLength = strPreFileData.GetLength(); #ifdef _UNICODE pHttpFile->Write( W2A( strPreFileData ), tmpLength ); #else pHttpFile->Write( (LPSTR)(LPCSTR)strPreFileData, tmpLength ); #endif curLength = curLength + tmpLength; FireOnUploadProgress((float)curLength/(dwTotalRequestLength + 1)); dwReadLength = -1; while (0 != dwReadLength) { dwReadLength = localFile.Read( pBuffer, dwChunkLength ); if ( 0 != dwReadLength ) { pHttpFile->Write( pBuffer, dwReadLength ); } curLength = curLength + dwReadLength; FireOnUploadProgress((float)curLength/(dwTotalRequestLength + 1)); } tmpLength = strPostFileData.GetLength(); #ifdef _UNICODE pHttpFile->Write( W2A( strPostFileData ), tmpLength ); #else pHttpFile->Write( (LPSTR)(LPCSTR)strPostFileData, tmpLength ); #endif curLength = curLength + tmpLength; FireOnUploadProgress((float)curLength/(dwTotalRequestLength + 1)); pHttpFile->EndRequest( HSR_SYNC ); } catch( CException* ew ) { ew->Delete(); if (NULL != pBuffer) { free(pBuffer); } localFile.Close(); pHttpFile->Close(); delete pHttpFile; pHttpConnection = NULL; session.Close(); FireOnError("上传文件中出现异常,请关闭本页重新调用此功能!"); return -1; } localFile.Close(); if (NULL != pBuffer) { free(pBuffer); } DWORD dwStatusCode = 200; pHttpFile->QueryInfoStatusCode(dwStatusCode); if(200 != dwStatusCode) {//HTTP请求失败 pHttpFile->Close(); delete pHttpFile; pHttpConnection = NULL; session.Close(); FireOnError("访问服务器失败!"); return -1; } try { dwResponseLength = pHttpFile->GetLength(); while ( 0 != dwResponseLength ) { szResponse = (LPSTR)malloc( dwResponseLength + 1 ); szResponse[dwResponseLength] = '\0'; pHttpFile->Read( szResponse, dwResponseLength ); strResponse += szResponse; free( szResponse ); dwResponseLength = pHttpFile->GetLength(); } } catch( CException* er ) { er->Delete(); pHttpFile->Close(); delete pHttpFile; pHttpConnection = NULL; session.Close(); FireOnError("读取服务器返回信息失败!"); return -1; } if(strResponse != "1") { lFileSize = -1; } pHttpFile->Close(); delete pHttpFile; pHttpConnection = NULL; session.Close(); } catch( CException* e ) { e->Delete(); return -1; } return lFileSize;}程序不太完整,凑合看吧; applet使用java.net.HttpURLConnection访问我的servlet,将包含参数的对象通过 ObjectOutputStream传递给servlet,servlet再通过ObjectInputStream获得对象。查询完成后,servlet通过new ObjectOutputStream(response.getOutputStream).writeObject()将数据写过去。我是这么打算的不知道这个思路可以不可以 这是客户端发送请求的代码,但是服务器端的servlet应该怎么对应客户端的请求呢import java.net.*;import java.io.*;public class HttpUpload { public static void main(String[] args) throws Exception { HttpURLConnection conn = null; BufferedReader br = null; DataOutputStream dos = null; DataInputStream inStream = null; InputStream is = null; OutputStream os = null; boolean ret = false; String StrMessage = ""; String exsistingFileName = "C:\\Documents and Settings\\system\\桌面\\TestUpload.txt"; String lineEnd = "\r\n"; String twoHyphens = "--"; String boundary = "*****"; int bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize = 1 * 1024 * 1024; String responseFromServer = ""; String urlString = "http://localhost:8080/YanZhengMa/uploadservlet"; try { //------------------ CLIENT REQUEST FileInputStream fileInputStream = new FileInputStream(new File(exsistingFileName)); // open a URL connection to the Servlet URL url = new URL(urlString); // Open a HTTP connection to the URL conn = (HttpURLConnection) url.openConnection(); // Allow Inputs conn.setDoInput(true); // Allow Outputs conn.setDoOutput(true); // Don't use a cached copy. conn.setUseCaches(false); // Use a post method. conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); dos = new DataOutputStream(conn.getOutputStream()); dos.writeBytes(twoHyphens + boundary + lineEnd); dos.writeBytes("Content-Disposition: form-data; name=\"uploadfile\";" + " filename=\"" + exsistingFileName + "\"" + lineEnd); dos.writeBytes(lineEnd); // create a buffer of maximum size bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); buffer = new byte[bufferSize]; // read file and write it into form... bytesRead = fileInputStream.read(buffer, 0, bufferSize); while (bytesRead > 0) { dos.write(buffer, 0, bufferSize); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); bytesRead = fileInputStream.read(buffer, 0, bufferSize); } // send multipart form data necesssary after file data... dos.writeBytes(lineEnd); dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); // close streams fileInputStream.close(); dos.flush(); dos.close(); } catch (MalformedURLException ex) { System.out.println("From ServletCom CLIENT REQUEST:" + ex); } catch (IOException ioe) { System.out.println("From ServletCom CLIENT REQUEST:" + ioe); } //------------------ read the SERVER RESPONSE try { inStream = new DataInputStream(conn.getInputStream()); String str; while ((str = inStream.readLine()) != null) { System.out.println("Server response is: " + str); System.out.println(""); } inStream.close(); } catch (IOException ioex) { System.out.println("From (ServerResponse): " + ioex); } }} 回复下哦, 可以通过HTTP协议,或者Socket 协议 http://download.csdn.net/source/1436214可以下载看看!! 解决了,在服务器端写个servlet,客户端用java.NET.URL把文件用数据流写到请求里,servlet处理请求就行了,谢谢各位 关于jquery clone的问题? hibernate中 could not resolve property servlet jsp基于请求的数据共享问题 字符串输出问题 连接不上sql数据库? JSP有什么可视化的程序设计工具? 想找个jsp的回复帖子的源代码,却一直找不到。真郁闷 在线等待《对等网络编程源代码解析》一书的配套光盘可否上传一份给我 类型转换简单问题(30分) 一个小小的调查 关于Hql的问题 关于servlet
要不就模拟http请求,去请求某个servlet,对servlet写你的文件流!
这是一个思路,你swt写的程序应该通过sockt与服务器通信的吧,如果你要用servlet,应该是要模拟HTTP请求的。
struts2有专门的上传组件,你可以去查下,很好用
//以下为保存文件,视情况修改
String file = getFile1();
System.out.print(file);
System.out.print(getfileFileName());
if(null!=file);
{
FileOutputStream outputStream = new FileOutputStream("上传服务器目录" + "文件名");
FileInputStream fileIn = new FileInputStream(file);
byte[] buffer = new byte[1024];
int len;
while ((len = fileIn.read(buffer)) > 0);
{
outputStream.write(buffer, 0, len);;
}
fileIn.close();;
outputStream.close();;
}
如果是WebApp的话你就模拟一个Http上传文件的请求。
我做过VC和Servlet通信的东西,原理上差不多,就是模拟Http请求;你可以参考一下;
CString MakeRequestHeaders( CString& strBoundary )
{
CString strFormat;
CString strData;
strFormat = _T( "Content-Type: multipart/form-data; boundary=%s\r\n" );
strData.Format( strFormat, strBoundary );
return strData;
}CString MakePreFileData( CString& strBoundary, CString& strFileName )
{
CString strFormat;
CString strData;
strFormat += _T( "--%s" );
strFormat += _T( "\r\n" );
strFormat += _T( "Content-Disposition: form-data; name=\"file\"; filename=\"%s\"" );
strFormat += _T( "\r\n" );
strFormat += _T( "Content-Type: application/x-www-form-urlencoded" );
strFormat += _T( "\r\n\r\n");
strData.Format( strFormat, strBoundary, strFileName );
return strData;
}int GetPreDateLenth ( CString& strBoundary )
{
CString strFormat;
CString strData;
strFormat += _T( "--%s" );
strFormat += _T( "\r\n" );
strFormat += _T( "Content-Disposition: form-data; name=\"file\"; filename=\"\"" );
strFormat += _T( "\r\n" );
strFormat += _T( "Content-Type: application/x-www-form-urlencoded" );
strFormat += _T( "\r\n\r\n");
strData.Format( strFormat, strBoundary );
return strData.GetLength();
}
CString MakePostFileData( CString& strBoundary )
{
CString strFormat;
CString strData;
strFormat = _T( "--%s--" );
strData.Format( strFormat, strBoundary );
return strData;
}
long CWISH_FileTransferCtrl::UploadFile(LPCTSTR httpHost, short httpPort, LPCTSTR httpUrl, LPCTSTR filePath)
{
// TODO: Add your dispatch handler code here
long lFileSize = 0;
try
{
CString host = httpHost;
INTERNET_PORT nPort = httpPort;
CString url = httpUrl;
url.Replace('\\','/');
CString local = filePath;
local.Replace('/','\\');
CInternetSession session;
CHttpConnection *pHttpConnection = NULL;
CHttpFile* pHttpFile;
CString strHTTPBoundary;
CString strPreFileData;
CString strPostFileData;
DWORD dwTotalRequestLength;
DWORD dwChunkLength;
DWORD dwReadLength;
DWORD dwResponseLength;
void* pBuffer;
LPSTR szResponse;
CString strResponse;
DWORD tmpLength = 0;
DWORD curLength = 0;
CFile localFile;
if(FALSE == localFile.Open(local, CFile::modeRead | CFile::shareDenyNone))
{
FireOnError("本地文件\"" + local + "\"无法打开!");
return -1;
}
lFileSize = localFile.GetLength();
strHTTPBoundary = newGUID();
strPreFileData = MakePreFileData(strHTTPBoundary, local);
strPostFileData = _T("\r\n") + MakePostFileData(strHTTPBoundary);
dwTotalRequestLength = strPreFileData.GetLength() + lFileSize + strPostFileData.GetLength();
dwChunkLength = 64 * 1024;
pBuffer = malloc( dwChunkLength );
if (NULL == pBuffer)
{
localFile.Close();
FireOnError("组件申请内存空间失败!");
return -1;
}
pHttpConnection = session.GetHttpConnection( host, nPort );
pHttpFile = pHttpConnection->OpenRequest( CHttpConnection::HTTP_VERB_POST, url );
pHttpFile->AddRequestHeaders( MakeRequestHeaders( strHTTPBoundary ) );
try
{
pHttpFile->SendRequestEx( dwTotalRequestLength, HSR_SYNC | HSR_INITIATE );
FireOnUploadProgress(0);
tmpLength = strPreFileData.GetLength();
#ifdef _UNICODE
pHttpFile->Write( W2A( strPreFileData ), tmpLength );
#else
pHttpFile->Write( (LPSTR)(LPCSTR)strPreFileData, tmpLength );
#endif
curLength = curLength + tmpLength;
FireOnUploadProgress((float)curLength/(dwTotalRequestLength + 1));
dwReadLength = -1;
while (0 != dwReadLength)
{
dwReadLength = localFile.Read( pBuffer, dwChunkLength );
if ( 0 != dwReadLength )
{
pHttpFile->Write( pBuffer, dwReadLength );
}
curLength = curLength + dwReadLength;
FireOnUploadProgress((float)curLength/(dwTotalRequestLength + 1));
}
tmpLength = strPostFileData.GetLength();
#ifdef _UNICODE
pHttpFile->Write( W2A( strPostFileData ), tmpLength );
#else
pHttpFile->Write( (LPSTR)(LPCSTR)strPostFileData, tmpLength );
#endif
curLength = curLength + tmpLength;
FireOnUploadProgress((float)curLength/(dwTotalRequestLength + 1));
pHttpFile->EndRequest( HSR_SYNC );
}
catch( CException* ew )
{
ew->Delete();
if (NULL != pBuffer)
{
free(pBuffer);
}
localFile.Close();
pHttpFile->Close();
delete pHttpFile;
pHttpConnection = NULL;
session.Close();
FireOnError("上传文件中出现异常,请关闭本页重新调用此功能!");
return -1;
}
localFile.Close();
if (NULL != pBuffer)
{
free(pBuffer);
} DWORD dwStatusCode = 200;
pHttpFile->QueryInfoStatusCode(dwStatusCode);
if(200 != dwStatusCode)
{//HTTP请求失败
pHttpFile->Close();
delete pHttpFile;
pHttpConnection = NULL;
session.Close();
FireOnError("访问服务器失败!");
return -1;
}
try
{
dwResponseLength = pHttpFile->GetLength();
while ( 0 != dwResponseLength )
{
szResponse = (LPSTR)malloc( dwResponseLength + 1 );
szResponse[dwResponseLength] = '\0';
pHttpFile->Read( szResponse, dwResponseLength );
strResponse += szResponse;
free( szResponse );
dwResponseLength = pHttpFile->GetLength();
}
}
catch( CException* er )
{
er->Delete();
pHttpFile->Close();
delete pHttpFile;
pHttpConnection = NULL;
session.Close();
FireOnError("读取服务器返回信息失败!");
return -1;
}
if(strResponse != "1")
{
lFileSize = -1;
}
pHttpFile->Close();
delete pHttpFile;
pHttpConnection = NULL;
session.Close();
}
catch( CException* e )
{
e->Delete();
return -1;
}
return lFileSize;
}
程序不太完整,凑合看吧;
我是这么打算的不知道这个思路可以不可以
import java.net.*;
import java.io.*;public class HttpUpload { public static void main(String[] args)
throws Exception {
HttpURLConnection conn = null;
BufferedReader br = null;
DataOutputStream dos = null;
DataInputStream inStream = null; InputStream is = null;
OutputStream os = null;
boolean ret = false;
String StrMessage = "";
String exsistingFileName = "C:\\Documents and Settings\\system\\桌面\\TestUpload.txt";
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
String responseFromServer = "";
String urlString = "http://localhost:8080/YanZhengMa/uploadservlet";
try {
//------------------ CLIENT REQUEST
FileInputStream fileInputStream = new FileInputStream(new
File(exsistingFileName));
// open a URL connection to the Servlet
URL url = new URL(urlString);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
// Allow Inputs
conn.setDoInput(true);
// Allow Outputs
conn.setDoOutput(true);
// Don't use a cached copy.
conn.setUseCaches(false);
// Use a post method.
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploadfile\";"
+ " filename=\"" + exsistingFileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// close streams
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
System.out.println("From ServletCom CLIENT REQUEST:" + ex);
} catch (IOException ioe) {
System.out.println("From ServletCom CLIENT REQUEST:" + ioe);
}
//------------------ read the SERVER RESPONSE
try {
inStream = new DataInputStream(conn.getInputStream());
String str;
while ((str = inStream.readLine()) != null) {
System.out.println("Server response is: " + str);
System.out.println("");
}
inStream.close();
} catch (IOException ioex) {
System.out.println("From (ServerResponse): " + ioex);
}
}
}
可以下载看看!!