pie*_*rus 4 java rest jersey fileinputstream
我正在开发一个使用Dropbox API的Jersey服务.
我需要将一个通用文件发布到我的服务中(该服务可以管理各种文件,也可以使用Dropbox API).
客户端
所以,我实现了一个简单的客户端:
FileInputStream并使用字节缓冲区在连接的输出流上写入文件.这是客户端测试代码.
public class Client {
public static void main(String args[]) throws IOException, InterruptedException {
String target = "http://localhost:8080/DCService/REST/professor/upload";
URL putUrl = new URL(target);
HttpURLConnection connection = (HttpURLConnection) putUrl.openConnection();
connection.setDoOutput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("content-Type", "application/pdf");
OutputStream os = connection.getOutputStream();
InputStream is = new FileInputStream("welcome.pdf");
byte buf[] = new byte[1024];
int len;
int lung = 0;
while ((len = is.read(buf)) > 0) {
System.out.print(len);
lung += len;
is.read(buf);
os.write(buf, 0, len);
}
}
}
Run Code Online (Sandbox Code Playgroud)
服务器端
我有一个方法:
InputStream一个参数,以下代码实现了一种接收特定PDF文件的测试方法.
@PUT
@Path("/upload")
@Consumes("application/pdf")
public Response uploadMaterial(InputStream is) throws IOException {
String name = "info";
String type = "exerc";
String description = "not defined";
Integer c = 10;
Integer p = 131;
File f = null;
try {
f = new File("welcome.pdf");
OutputStream out = new FileOutputStream(f);
byte buf[] = new byte[1024];
int len;
while ((len = is.read(buf)) > 0)
out.write(buf, 0, len);
out.close();
is.close();
System.out.println("\nFile is created........");
} catch (IOException e) {
throw new WebApplicationException(Response.Status.BAD_REQUEST);
}
//I need to pass a java.io.file object to this method
professorManager.uploadMaterial(name, type, description, c,p, f);
return Response.ok("<result>File " + name + " was uploaded</result>").build();
}
Run Code Online (Sandbox Code Playgroud)
此实现仅适用于文本文件.如果我尝试发送一个简单的PDF,则接收的文件不可读(在我将其保存在磁盘上之后).
我怎样才能满足我的要求?谁能建议我解决方案?
你的客户端代码有问题.
while ((len = is.read(buf)) > 0) {
...
is.read(buf);
...
}
Run Code Online (Sandbox Code Playgroud)
你在每次迭代中读取InputStream 两次.read从循环体中删除语句,你会没事的.
您还说过,您的问题中提供的代码适用于文本文件.我认为这也不起作用.从您尝试上传的文件中读取两次意味着您只上传了其中一半的内容.半个文本文件仍然是文本文件,但半个PDF只是垃圾,所以你无法打开后者.如果上传和保存的文本文件的内容与原始文件相同,则应仔细检查.
| 归档时间: |
|
| 查看次数: |
2972 次 |
| 最近记录: |