|
|
近日在工作中要用到图片服务器的功能,由于图片服务器和后台系统不在同一个域下,导致上传文件后JS无法跨域处理上传结果。解决办法就是通用的proxy方法,在后台系统写一个代理方法处理上传文件并返回结果。在Action中用流交互数据,可始终无法上传,图片服务器报500,在网上找了资料才知道输入到文件服务器的流要稍微处理下,否则协议不完整导致功能无法完成。附代码:(11-13行的POST、Connection、contentType设置非常重要)
String fileServerUrl = "http://img.aaa.com/uploadFile.jsp"; InputStream is = request.getInputStream(); String contentType = request.getContentType(); URL url = new URL(fileServerUrl); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Content-Type", contentType); conn.connect(); OutputStream connOs = conn.getOutputStream(); byte[] b = new byte[1024]; int num=0;while((num=is.read(b)) != -1){ connOs.write(b,0,num); } InputStream connIs=conn.getInputStream(); BufferedReader connBr = new BufferedReader(new InputStreamReader(connIs)); StringBuffer sb = new StringBuffer(); String str; while((str=connBr.readLine())!=null){ sb.append(str); } log.info("结果------"+sb); connOs.close(); connBr.close(); connIs.close();
参考的源码是一个老外写的,“用JAVA程序封装一个HTTP上传请求上传文件”,参考代码如下:
import java.io.*;import java.net.*;public class ServletCom {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:\\account.xls";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/FileUpload/requestupload";try {// ------------------ CLIENT REQUESTFileInputStream fileInputStream = new FileInputStream(new File(exsistingFileName));// open a URL connection to the ServletURL url = new URL(urlString);// Open a HTTP connection to the URLconn = (HttpURLConnection) url.openConnection();// Allow Inputsconn.setDoInput(true);// Allow Outputsconn.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=\"upload\";"+ " filename=\"" + exsistingFileName + "\"" + lineEnd);dos.writeBytes(lineEnd);// create a buffer of maximum sizebytesAvailable = 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 streamsfileInputStream.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 RESPONSEtry {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);}}} |
|