我有一个用Java运行的客户端应用程序,它将HTTP REST命令发送到c#中的Web服务。
客户端从服务器下载文件,效果非常好。
这是我的文件传输代码:
Java客户端
public void downloadFile(String fileUrl, String fileName, String filePath) throws IOException{
int bytesRead;
URL url = new URL(fileUrl);
BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
byte[] fileBuffer = new byte[1024];
while ((bytesRead = bis.read(fileBuffer)) != -1) {
bos.write(fileBuffer, 0, bytesRead);
}
bos.close();
bis.close();
}
C#网络服务
[WebGet(UriTemplate = "SendFile/{clientID}/{fileName}")]
public Stream sendFile(String clientID, String fileName)
{
WebOperationContext.Current.OutgoingResponse.Headers.Add(HttpResponseHeader.Expires, DateTime.UtcNow.ToString("ddd, dd MMM yyyy HH:mm:ss 'GMT'"));
WebOperationContext.Current.OutgoingResponse.ContentType = "application/pdf";
Stream ms = File.OpenRead(@jobRepPath + fileName.Replace("___", "."));
return ms;
}
现在,基于此,我想设置方法来恢复下载损坏的下载。
我试过这段代码:
Java客户端
public void resumeBrokenDownload(String fileUrl, String fileName, String filePath, long fileLength) throws IOException{
int bytesRead;
URL url = new URL(fileUrl);
BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath, true));
byte[] fileBuffer = new byte[1024];
while ((bytesRead = bis.read(fileBuffer)) != -1) {
bos.write(fileBuffer, 0, bytesRead);
}
bos.close();
bis.close();
}
C#网络服务
[WebGet(UriTemplate = "ResumeDownload/{clientID}/{fileName}/{startByte}")]
public Stream resumeDownload(String clientID, String fileName, String startByte)
{
Stream ms = File.OpenRead(@jobRepPath + fileName.Replace("___", "."));
var memoryStream = new MemoryStream();
ms.CopyTo(memoryStream);
Byte[] byteFile = memoryStream.ToArray();
MemoryStream stream = new MemoryStream();
stream.Write(byteFile, Convert.ToInt32(startByte), byteFile.Length);
WebOperationContext.Current.OutgoingResponse.Headers.Add(HttpResponseHeader.Expires, DateTime.UtcNow.ToString("ddd, dd MMM yyyy HH:mm:ss 'GMT'"));
WebOperationContext.Current.OutgoingResponse.ContentType = "application/pdf";
return stream;
}
REST URL中传递的startByte值是客户端已经接收的文件部分的长度。
但这似乎根本不起作用,我从服务器收到一个空流。
有没有人知道如何让这段代码工作,或者更好的方法呢?
答案 0 :(得分:0)
我终于解决了我在this tutorial中修改示例的问题。
对于那些对我的解决方案感兴趣的人,我更改了c#web服务的代码:
[WebGet(UriTemplate = "ResumeDownload/{clientID}/{fileName}/{startByte}")]
public Stream resumeDownload(String clientID, String fileName, String startByte)
{
MemoryStream responseStream = new MemoryStream();
Stream fileStream = File.Open(@jobRepPath + fileName.Replace("___", "."), FileMode.Open);
fileStream.Seek(Convert.ToInt32(startByte), SeekOrigin.Begin);
int length = (int)(fileStream.Length - Convert.ToInt32(startByte));
byte[] buffer = new byte[length];
fileStream.Read(buffer, 0, length);
responseStream.Write(buffer, 0, length);
fileStream.Close();
responseStream.Position = 0;
return responseStream;
}