2014-09-17 21 views
16

Tôi đang tạo POC cho dịch vụ Web RESTFUL bằng Spring 4.0. Nó hoạt động tốt nếu chúng ta chỉ chuyển chuỗi hoặc bất kỳ một kiểu dữ liệu cơ bản nào khác.Mùa xuân: Tải lên tệp Dịch vụ Web RESTFUL

@RequestMapping(value="/upload/file", method=RequestMapping.post) 
public String uploadFile(@RequestParam("fileName", required=false) String fileName){ 
    logger.info("initialization of object"); 
    //---------------------------------------- 

    System.out.Println("name of File : " + fileName); 

    //---------------------------------------- 
} 

Điều này làm việc tốt. nhưng nếu tôi muốn vượt qua dòng byte hoặc đối tượng tệp để hoạt động, làm thế nào tôi có thể viết hàm này có các tham số này? và Làm thế nào tôi có thể viết Khách hàng có cung cấp luồng byte đi qua?

@RequestMapping(value="/upload/file", method=RequestMapping.post) 
public String uploadFile(@RequestParam("file", required=false) byte [] fileName){ 
    //--------------------- 
    // 
} 

Tôi đã thử mã này nhưng nhận được 415 lỗi.

@RequestMapping(value = "/upload/file", method = RequestMethod.POST, consumes="multipart/form-data") 
public @ResponseBody String uploadFileContentFromBytes(@RequestBody MultipartFormDataInput input, Model model) { 
    logger.info("Get Content. "); 
    //------------ 
    } 

Khách hàng Mã - Sử dụng apache HttpClient

private static void executeClient() { 
    HttpClient client = new DefaultHttpClient(); 
    HttpPost postReqeust = new HttpPost(SERVER_URI + "/file"); 

    try{ 
     // Set Various Attributes 
     MultipartEntity multipartEntity = new MultipartEntity(); 
     multipartEntity.addPart("fileType" , new StringBody("DOCX")); 

     FileBody fileBody = new FileBody(new File("D:\\demo.docx"), "application/octect-stream"); 
     // prepare payload 
     multipartEntity.addPart("attachment", fileBody); 

     //Set to request body 
     postReqeust.setEntity(multipartEntity); 

     HttpResponse response = client.execute(postReqeust) ; 

     //Verify response if any 
     if (response != null) 
     { 
      System.out.println(response.getStatusLine().getStatusCode()); 
     } 

    } 
    catch(Exception ex){ 
     ex.printStackTrace(); 
    } 
+0

Từ quan điểm máy chủ của xem, nó sẽ nhận được một 'MultipartFile'. Từ quan điểm HTTP, nó sẽ truyền 'multipart/form-data'. Và từ quan điểm của khách hàng ... nó sẽ phụ thuộc vào thư viện khách hàng ... –

+0

IMHO, bạn không nên sử dụng chú thích '@ RequestBody' khi sử dụng' multipart/form-data', nhưng bạn nên xem xét Tham khảo mùa xuân Hướng dẫn sử dụng để xem cách cấu hình một ứng dụng để xử lý việc tải lên tệp. –

+0

@serge: Tôi đã thử điều này nhưng phải đối mặt với lỗi 415. xin vui lòng đề nghị tôi liên kết tham khảo tốt. – Ronnie

Trả lời

25

Bạn có thể tạo ra dịch vụ còn lại của bạn như dưới đây.

@RequestMapping(value="/upload", method=RequestMethod.POST) 
    public @ResponseBody String handleFileUpload( 
      @RequestParam("file") MultipartFile file){ 
      String name = "test11"; 
     if (!file.isEmpty()) { 
      try { 
       byte[] bytes = file.getBytes(); 
       BufferedOutputStream stream = 
         new BufferedOutputStream(new FileOutputStream(new File(name + "-uploaded"))); 
       stream.write(bytes); 
       stream.close(); 
       return "You successfully uploaded " + name + " into " + name + "-uploaded !"; 
      } catch (Exception e) { 
       return "You failed to upload " + name + " => " + e.getMessage(); 
      } 
     } else { 
      return "You failed to upload " + name + " because the file was empty."; 
     } 
    } 

Và đối với phía khách hàng, hãy làm như bên dưới.

import java.io.File; 
import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
import org.apache.http.HttpVersion; 
import org.apache.http.client.HttpClient; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.entity.mime.MultipartEntity; 
import org.apache.http.entity.mime.content.ContentBody; 
import org.apache.http.entity.mime.content.FileBody; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.apache.http.params.CoreProtocolPNames; 
import org.apache.http.util.EntityUtils; 


public class Test { 
    public static void main(String[] args) throws Exception { 
    HttpClient httpclient = new DefaultHttpClient(); 
    httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); 

    HttpPost httppost = new HttpPost("http://localhost:8080/upload"); 
    File file = new File("C:\\Users\\Kamal\\Desktop\\PDFServlet1.pdf"); 

    MultipartEntity mpEntity = new MultipartEntity(); 
    ContentBody cbFile = new FileBody(file, "multipart/form-data"); 
    mpEntity.addPart("file", cbFile); 


    httppost.setEntity(mpEntity); 
    System.out.println("executing request " + httppost.getRequestLine()); 
    HttpResponse response = httpclient.execute(httppost); 
    HttpEntity resEntity = response.getEntity(); 

    System.out.println(response.getStatusLine()); 
    if (resEntity != null) { 
     System.out.println(EntityUtils.toString(resEntity)); 
    } 
    if (resEntity != null) { 
     resEntity.consumeContent(); 
    } 

    httpclient.getConnectionManager().shutdown(); 
    } 
} 
+0

Tôi đã thử điều này nhưng lại phải đối mặt với 500 mã lỗi. 'java.lang.IllegalStateException: Yêu cầu hiện tại không thuộc loại [org.springframework.web.multipart.MultipartRequest]: org.apache.catalina.connector.RequestFacade @ 7de7432b' Tôi đã cập nhật câu hỏi của mình với mã Client. Bây giờ tôi rất bối rối. : ( – Ronnie

+0

Những gì bạn đang sử dụng ở cuối khách hàng? Bạn có thể chỉ cung cấp một số mã máy khách, từ nơi bạn đang yêu cầu dịch vụ này không? – RE350

+0

Tôi đã cập nhật câu hỏi ở đó bạn có thể tìm thấy mã máy khách. – Ronnie

2

<bean id="multipartResolver" 
 
\t class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> 
 
</bean>

mã này requred

+0

Cảm ơn bạn đã đề xuất. nhưng nó không phải là vấn đề. MultipartResolver Bean đã có sẵn. Vui lòng kiểm tra câu trả lời mà tôi đã chấp nhận. – Ronnie

+0

mục đích của tập lệnh này là gì? – kn3l

Các vấn đề liên quan