这是我调用java方法的jsp
<%
PDFFileUploader.generatePDcFile(); //Calls the PDF method;
%>
这是我的PDFFileUploader代码
public class PDFFileUploader {
static final String UPLOAD_URL = "http://localhost:7080/pdf/GetPDFFile";
static final int BUFFER_SIZE = 4096;
public static void generatePDcFile() throws IOException
{
System.out.println("Inside generatePDC File");
// takes file path from first program's argument
String filePath = "H:/report1.pdf";
File uploadFile = new File("H:/report1.pdf");
System.out.println("File to upload: " + filePath);
// creates a HTTP connection
URL url = new URL(UPLOAD_URL);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
httpConn.setUseCaches(false);
httpConn.setDoOutput(true);
httpConn.setRequestMethod("POST");
// sets file name as a HTTP header
httpConn.setRequestProperty("fileName", uploadFile.getName());
// opens output stream of the HTTP connection for writing data
OutputStream outputStream = httpConn.getOutputStream();
// Opens input stream of the file for reading data
FileInputStream inputStream = new FileInputStream(uploadFile);
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead = -1;
System.out.println("Start writing data...");
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
System.out.println("Data was written.");
outputStream.close();
inputStream.close();
//Read pdc file
//FileOutputStream test = new FileOutputStream("test");
// always check HTTP response code from server
InputStream test = null;
File pdcFile = new File("H:/report123.pdf");
FileOutputStream outputStreamTest = new FileOutputStream(pdcFile);
//byte[] bufferTest = new byte[BUFFER_SIZE];
//int bytesReadTest = -1;
//final OutputStream ostream = new FileOutputStream("/tmp/data.pdc");
int responseCode = httpConn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
// reads server's response
/* BufferedReader reader = new BufferedReader(new InputStreamReader(
httpConn.getInputStream()));*/
test = httpConn.getInputStream();
String message= httpConn.getResponseMessage();
System.out.println("Message is///"+message);
System.out.println("Header :: "+httpConn.getHeaderField(0));
final byte[] bufferTest = new byte[1024*14];
while (true) {
int len = test.read(bufferTest);
if (len <= 0) {
break;
}
outputStreamTest.write(bufferTest, 0, len);
}
outputStreamTest.close();
test.close();
String fileName = "";
String disposition = httpConn.getHeaderField("Content-Disposition");
// extracts file name from header field
int index = disposition.indexOf("filename=");
if (index > 0) {
fileName = disposition.substring(index + 10,
disposition.length() - 1);
}
System.out.println("Get File Name"+fileName);
/* Map<String, List<String>> map = httpConn.getHeaderFields();
for (Map.Entry<String, List<String>> entry : map.entrySet()) {
System.out.println("Key : " + entry.getKey() +
" ,Value : " + entry.getValue());
}*/
// String response = reader.readLine();
//System.out.println("Server's response: " + response);
} else {
System.out.println("Server returned non-OK code: " + responseCode);
}
}
从这里通过上面提供的URL调用servlet,为getPDFFile Servlet的doPost方法提供代码
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
// Gets file name for HTTP header
String fileName = request.getHeader("fileName");
File saveFile = new File(SAVE_DIR + fileName);
// prints out all header values
System.out.println("===== Begin headers =====");
Enumeration<String> names = request.getHeaderNames();
while (names.hasMoreElements()) {
String headerName = names.nextElement();
System.out.println(headerName + " = " + request.getHeader(headerName));
}
System.out.println("===== End headers =====\n");
// opens input stream of the request for reading data
InputStream inputStream = request.getInputStream();
// opens an output stream for writing file
/*FileOutputStream outputStream = new FileOutputStream(saveFile);*/
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead = -1;
System.out.println("Receiving data...");
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
System.out.println("Data received.");
outputStream.close();
inputStream.close();
System.out.println("File written to: " + saveFile.getAbsolutePath());
int processStatus = 0;
//temp file (used for conversion)
/* boolean success = (new File
(saveFile.getAbsolutePath())).delete();
System.out.println("File deleted :: "+success);
//delete pdc file too
boolean successtemp = (new File
(recentlyConvertedFile.getAbsolutePath())).delete();
System.out.println("File deleted :: "+successtemp);*/
response.setContentType("application/octet-stream" );
response.setHeader("Content-Disposition","inline;filename=\"" + saveFile.getName() + "\"");
response.setContentLength((int) saveFile.length());
OutputStream os = response.getOutputStream();
FileInputStream fis = new FileInputStream(saveFile);
//op.write(response.toString().getBytes(Charset.forName("utf-8")));
//op.flush();
try {
int byteRead = 0;
while ((byteRead = fis.read()) != -1) {
os.write(buffer, 0, byteRead);
}
os.flush();
} catch (Exception excp) {
excp.printStackTrace();
} finally {
os.close();
fis.close();
}
// sends response to client
//response.getWriter().print("UPLOAD DONE");
}
文件正在下载,但是没有打开生成的pdf与原始文件的大小相同,我已经采取了文本文件并将内容打印到另一个文件,它似乎只读取文本文件的第一行作为输入< / p>
答案 0 :(得分:0)
将文件从servlet返回到客户端的最终循环如下所示:
while ((byteRead = fis.read()) != -1) {
os.write(buffer, 0, byteRead);
}
您似乎忘记在buffer
中使用fis.read()
,这应该是这样的:
while ((byteRead = fis.read(buffer)) != -1) {
os.write(buffer, 0, byteRead);
}
因此,您发送回尽可能多的缓冲区内容副本,因为fis返回数字!= -1
。
BTW:你的servlet将收到的数据放入ByteArrayOutputStream outputStream
并删除它,但它声称已将它们写入最终尝试返回给调用者的文件中。