跨伺服器上傳檔案方式

來源:互聯網
上載者:User

標籤:commons   while   amp   message   final   cli   http   方式   url   

跨伺服器上傳檔案的方式有很多,其中一種是使用在中間伺服器上使用臨時檔案的方式進行儲存後再發送到另一個伺服器上,實現檔案上傳。

問題點:中間儲存臨時檔案,還需要不定時的進行檔案清理,比較麻煩

 

直接進行檔案的轉寄,使用byte[]數組方式直接進行檔案轉寄,然後,伺服器根據傳遞的byte[]數組進行轉檔案方式,使用httpclient方式將byte[]數組發送到服務端,特別注意的點在於,

發送的時候使用"content-type" = "application/json"發送到服務端,服務端使用@RequestBody byte[] bytes 進行方法接收,其他的一些參數如果還要傳遞,可以使用header將參數傳遞過去

package com.rainy.demo.utils;
import org.apache.commons.httpclient.HttpClient;import org.apache.commons.httpclient.HttpStatus;import org.apache.commons.httpclient.methods.ByteArrayRequestEntity;import org.apache.commons.httpclient.methods.PostMethod;import java.io.IOException;/** * Created by rainy on 2016/12/17. */public class UpImgUtils { public static String getPath(String url, String fileType, byte[] bytes) { String path = ""; try { PostMethod method = new PostMethod(url); method.setRequestHeader("Content-type" , "application/json"); method.setRequestHeader("fileType", fileType); HttpClient httpClient = new HttpClient(); method.setRequestEntity(new ByteArrayRequestEntity(bytes)); int HttpCode = httpClient.executeMethod(method); if (HttpCode != HttpStatus.SC_OK) { throw new IOException("Invalid HttpStatus: " + HttpCode); } path = method.getResponseBodyAsString(); } catch (IOException e) { System.err.println(e.getMessage()); } return path; }}

 

通常,SpringMVC 中使用 MultipartFile 進行檔案上傳,通過這樣的方法擷取到上傳過來檔案的byte[]數組

@RequestMapping("/upload")@ResponseBodypublic String uploadFile(HttpServletRequest request){    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;    MultipartFile file = multipartRequest.getFile("file");    byte[] bytes = null;    try {        bytes = file.getBytes();    } catch (IOException e) {        e.printStackTrace();    }    return null;}

伺服器端使用,使用該方法來擷取對應的上傳檔案byte[]數組

public String upLoad(@RequestBody byte[] inputData, HttpServletRequest request) {}

 

網友使用的byte[]數組轉檔案的方式,沒有試過,不過這個不是重點,重點在於中間轉寄點,只要能拿到byte[]數組,轉檔案還是比較容易的

public class T3 {        public static void main(String[] args){          String filePath = "E:\\softoon\\workspace_softoon\\TestMobile\\src\\1.docx";          String outFilePath = "E:\\softoon\\workspace_softoon\\TestMobile\\src";          String outFileName = "2.docx";                    getFile(getBytes(filePath),outFilePath,outFileName);      }        /**      * 獲得指定檔案的byte數組      */      public static byte[] getBytes(String filePath){          byte[] buffer = null;          try {              File file = new File(filePath);              FileInputStream fis = new FileInputStream(file);              ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);              byte[] b = new byte[1000];              int n;              while ((n = fis.read(b)) != -1) {                  bos.write(b, 0, n);              }              fis.close();              bos.close();              buffer = bos.toByteArray();          } catch (FileNotFoundException e) {              e.printStackTrace();          } catch (IOException e) {              e.printStackTrace();          }          return buffer;      }        /**      * 根據byte數組,組建檔案      */      public static void getFile(byte[] bfile, String filePath,String fileName) {          BufferedOutputStream bos = null;          FileOutputStream fos = null;          File file = null;          try {              File dir = new File(filePath);              if(!dir.exists()&&dir.isDirectory()){//判斷檔案目錄是否存在                  dir.mkdirs();              }              file = new File(filePath+"\\"+fileName);              fos = new FileOutputStream(file);              bos = new BufferedOutputStream(fos);              bos.write(bfile);          } catch (Exception e) {              e.printStackTrace();          } finally {              if (bos != null) {                  try {                      bos.close();                  } catch (IOException e1) {                      e1.printStackTrace();                  }              }              if (fos != null) {                  try {                      fos.close();                  } catch (IOException e1) {                      e1.printStackTrace();                  }              }          }      }  }

 

整體的使用方式已經寫出來了,用在什麼地方還需要討論,不過,這樣的實現方式還是很不錯的,減少了臨時檔案的存放,而且,代碼量減少很多。

 

跨伺服器上傳檔案方式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.