| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162 | package net.codejava.servlet; import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.util.Enumeration; import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse; /** * This servlet demonstrates how to receive file uploaded from the client * without using third-party upload library such as Commons File Upload. * @author www.codejava.net */public class ReceiveFileServlet extendsHttpServlet { staticfinal String SAVE_DIR ="E:/Test/Upload/"; staticfinal int BUFFER_SIZE = 4096; protectedvoid doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { // 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); byte[] buffer =new byte[BUFFER_SIZE]; intbytesRead = -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()); // sends response to client response.getWriter().print("UPLOAD DONE"); }} |
| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667 | import java.io.BufferedReader;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStreamReader;import java.io.OutputStream;import java.net.HttpURLConnection;import java.net.URL; /** * This program demonstrates how to upload files to a web server * using HTTP POST request without any HTML form. * @author www.codejava.net * */public class NonFormFileUploader { staticfinal String UPLOAD_URL ="http://localhost:8080/CodeWeb/ReceiveFileServlet"; staticfinal int BUFFER_SIZE = 4096; publicstatic void main(String[] args) throws IOException { // takes file path from first program's argument String filePath = args[0]; File uploadFile =new File(filePath); 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]; intbytesRead = -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(); // always check HTTP response code from server intresponseCode = httpConn.getResponseCode(); if(responseCode == HttpURLConnection.HTTP_OK) { // reads server's response BufferedReader reader =new BufferedReader(newInputStreamReader( httpConn.getInputStream())); String response = reader.readLine(); System.out.println("Server's response: "+ response); }else { System.out.println("Server returned non-OK code: "+ responseCode); } }} |
The important point here is we use an HttpURLConnection object to send an HTTP POST request to the server at URL of the servlet (identified by the constantUPLOAD_URL) and open the OutputStream of this connection to write byte arrays of the upload file. Path of this file is passed as the first argument of the program. Similarly to the servlet, we use a while loop to read/write byte arrays from/to the file’s input stream/request’s output stream. Finally, we read response from the server after closing both input/output streams by using the input stream of the request.
java NonFormFileUploader e:/Test/RecordAudio.wav
Here we pass a WAV audio file to be uploaded. The server will produce some output as the following screenshot:
From this log, we can examine values of all HTTP headers sent from the client. Almost of values are set by Java automatically, except thefilename is set from the client manually. And here is the output from the client program:
NOTE:Neither the server nor the client is playing with multipart request (which is standard for form-based upload). Note that the request’s content type is set toapplication/x-www-form-urlencoded instead of multipart/form-data.Thus the client program cannot be applied for the server which accepts multipart request. The server side must be implemented like theReceiveFileServletdoes.新闻热点
疑难解答