2016-03-13 51 views
-1

我有一個Web UI和一個基於spring的休息服務。UI有兩個按鈕上傳和下載。當上傳被調用時,一個調用去到我的REST服務。其餘的服務將獲得文件並存儲它在機器中。用Java存儲文件

瀏覽器(上載文件)---->服務(獲取文件和存儲文件)

我怎樣才能接收到的文件存儲在REST服務的我appliance.My骨架

@RequestMapping(value = "/file", produces = { MediaType.APPLICATION_OCTET_STREAM_VALUE}, method = RequestMethod.POST) 
    public void putFile(@RequestParam(value="fileName", required=false) File fileName,HttpServletRequest request,HttpServletResponse response) throws IOException{ 

    What do I do here ,How can I store the received file . 
    } 

另外從作爲請求的一部分,我的JavaScript可以發送文件到服務器?

+1

您可以編寫基於Spring的REST客戶端,但不知道如何將數據寫入文件?或者你認爲這是一個代碼寫作服務? – Raedwald

回答

1

您可以使用MultipartFile獲取Spring中的實際文件。

@RequestMapping(method = RequestMethod.POST, value = "/upload") 
public String handleFileUpload(@RequestParam("name") String name, 
           @RequestParam("file") MultipartFile file) { 
    ... 
} 

Here就是合適的例子。

0

假設該文件是在請求主體可用,也許是這樣的:

InputStream requestInputStream = request.getInputStream(); 
OutputStream fileOutputStream = new FileOutputStream(fileName); 

final int bufferSize = 4096; 
byte[] buffer = new byte[bufferSize]; 

int byteCount; 
while((byteCount=requestInputStream.read(buffer)) != 0) { 
    fileOutputStream.write(buffer, /*offset = 0*/ 0, byteCount); 
} 

fileOutputStream.close(); 
+0

如何將它存儲在某個地方說/ home/user/FileStorage –

+0

OutputStream fileOutputStream = new FileOutputStream(new File(「/ home/user/FileStorage/」)); – Atuos

0

試試這個。

@RequestMapping(value = "/file", method = RequestMethod.POST) 
public void putFile(HttpServletRequest request, HttpServletResponse response, @RequestParam CommonsMultipartFile[] fileUpload) throws Exception { 
    InputStream templateInputStream = null; 
    if (fileUpload != null && fileUpload.length > 0) { 
     for (CommonsMultipartFile aFile : fileUpload) { 
      templateInputStream = aFile.getInputStream(); 
      convertStreamToFile(templateInputStream, new File("/home/user/FileStorage/<filename>")); 
      templateInputStream.reset(); 
      break; 
     } 
    } 
} 

    public void convertStreamToFile(InputStream is, File file) throws IOException { 
     BufferedReader reader = new BufferedReader(new InputStreamReader(is)); 
     BufferedWriter fileWriter = new BufferedWriter(new FileWriter(file)); 
     String line = null; 
     while ((line = reader.readLine()) != null) { 
      fileWriter.write(line + "\n"); 
     } 
     fileWriter.flush(); 
     fileWriter.close(); 
     is.close(); 

    }