2017-05-04 42 views
0

我試圖通過HTTPUrlconnection發佈xlsx文件,在接收端我得到的文件,但同時在MS Excel中打開它說該文件已損壞,需要修復。我的代碼片段爲多部分後xlsx的多部分文章通過HTTPUrlConnection被破壞

class MultipartUtility { 
     private final Logger log = getLogger(MultipartUtility.class.getName()); 
     private static final String CRLF = "\r\n"; 
     private static final String CHARSET = "UTF-8"; 
     private static final int CONNECT_TIMEOUT = 1500000; 
     private static final int READ_TIMEOUT = 1000000; 
     private final HttpURLConnection connection; 
     private final OutputStream outputStream; 
     private final PrintWriter writer; 
     private final String boundary; 
     // for log formatting only 
     private final URL url; 
     private final long start; 

     public MultipartUtility(final String strUrl) throws IOException { 
      start = currentTimeMillis(); 
      URL url = new URL(strUrl); 
      this.url = url; 
      boundary = "---------------------------" + currentTimeMillis(); 
      connection = (HttpURLConnection) url.openConnection(); 
      connection.setConnectTimeout(CONNECT_TIMEOUT); 
      connection.setReadTimeout(READ_TIMEOUT); 
      connection.setRequestMethod("POST"); 
      connection.setRequestProperty("Accept-Charset", CHARSET); 
      connection.setRequestProperty("Content-Type","multipart/form-data; boundary=" + boundary); 
      connection.setUseCaches(false); 
      connection.setDoInput(true); 
      connection.setDoOutput(true); 
      outputStream = connection.getOutputStream(); 
      writer = new PrintWriter(new OutputStreamWriter(outputStream, CHARSET),true); 
     } 
     public void addFilePart(final String filePath)throws IOException { 
      String fieldName = "content"; 
      File uploadFile = new File(filePath); 
      final String fileName = uploadFile.getName(); 
      writer.append("--").append(boundary).append(CRLF) 
        .append("Content-Disposition: form-data; name=\"") 
        .append(fieldName).append("\"; filename=\"").append(fileName) 
        .append("\"").append(CRLF).append("Content-Type: ") 
        .append(guessContentTypeFromName(fileName)).append(CRLF) 
        .append("Content-Transfer-Encoding: binary").append(CRLF) 
        .append(CRLF); 

      writer.flush(); 
      outputStream.flush(); 
      try (final FileInputStream inputStream = new FileInputStream(uploadFile);) { 
       final byte[] buffer = new byte[4096]; 
       int bytesRead; 
       while ((bytesRead = inputStream.read(buffer)) != -1) { 
        outputStream.write(buffer, 0, bytesRead); 
       } 
       outputStream.flush(); 
      } 
      writer.append(CRLF); 
     } 


     public HashMap<Object, Object> finish() throws IOException { 
      writer.append(CRLF).append("--").append(boundary).append("--").append(CRLF); 
      writer.close(); 

      final int status = connection.getResponseCode(); 
      if (status != HTTP_OK) { 
       throw new IOException(format("{0} failed with HTTP status: {1}",url, status)); 
      } 
      try (final InputStream is = connection.getInputStream()) { 
       BufferedReader reader = new BufferedReader(new InputStreamReader(is)); 
       String sResponse; 
       StringBuilder responseBuilder = new StringBuilder(); 
       while ((sResponse = reader.readLine()) != null) { 
        responseBuilder = responseBuilder.append(sResponse); 
       } 
       HashMap respMap = new HashMap(); 
       respMap.put("RESP_MSG", responseBuilder.toString()); 
       respMap.put("RESP_CODE", status); 
       respMap.put("RESP_SIZE", responseBuilder.toString().length()); 
       log.log(INFO,format("{0} took {4} ms", url,(currentTimeMillis() - start))); 
       log.log(INFO,"status::::::"+status); 
       return respMap; 
      } finally { 
       connection.disconnect(); 
      } 
     } 
    } 

回答

0

我試圖執行您的代碼,並能夠成功從java程序上傳文件。 你報告的問題是我猜想由於文件的內容類型。如果您嘗試上傳.xlsx(MS Excel 2007),它會使數據變形並在讀取上傳的文件之前需要恢復。

如果您嘗試上傳.xls文件,它會正確上傳而不會發生任何變形,MS Excel會在沒有任何警告/錯誤的情況下打開此文件。

所以我建議打轉轉 writer.append( 「的Content-Type:」 + 「應用程序/ x-EXCEL」)

找到正確的內容類型是指: https://www.codeproject.com/Questions/481262/contentplustypeplusforplusxlsxplusfile

祝你好運

+0

你給的解決方法工作正常。非常感謝。 –