Asdfasf

Friday, October 12, 2012

Uploading File with Apache Commons File Upload

To upload file into server and reading uploaded file, we need following apache packages;

http://hc.apache.org/httpcomponents-client-ga/

http://commons.apache.org/fileupload/

Client code is as below, it is just posting a file and string parameter into a servlet:


 import java.io.File;  
 import java.io.IOException;  
 import org.apache.http.HttpResponse;  
 import org.apache.http.client.ClientProtocolException;  
 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.FileBody;  
 import org.apache.http.entity.mime.content.StringBody;  
 import org.apache.http.impl.client.DefaultHttpClient;  
 public class UploadFile {  
   public static void main(String[] args) throws ClientProtocolException, IOException {  
     HttpClient client = new DefaultHttpClient();  
     String url = "http://127.0.0.1:8080/servlet";  
     HttpPost post = new HttpPost(url);  
     File file = new File("c:\\sil\\SID.jpg");  
     MultipartEntity entity = new MultipartEntity();  
     entity.addPart("file", new FileBody(file));  
     entity.addPart("parameter", new StringBody("value"));      
     post.setEntity(entity);  
     HttpResponse response = client.execute(post);  
     System.out.println(response);  
   }  
 }  

How uploaded file and http parameter can be processed in servlet side?

  public SmsForm processRequest(HttpServletRequest request) throws IOException, ServletException {  
     String contentType = request.getContentType();      
     SmsForm smsForm = new SmsForm();          
     if ((contentType != null) && (contentType.startsWith("multipart/form-data"))) {  
       DiskFileUpload fu = new DiskFileUpload();  
       fu.setSizeMax(100000);  
       fu.setSizeThreshold(4096);  
       fu.setRepositoryPath(System.getProperty("java.io.tmpdir"));  
       try {  
         List fileItems = fu.parseRequest(request);  
         Iterator iter = fileItems.iterator();  
         while (iter.hasNext()) {  
           FileItem item = (FileItem) iter.next();  
           String fileName = item.getName();  
           if (item.getName() == null) {  
             String fieldName = item.getFieldName();              
             smsForm.setField(fieldName, item.getString());              
           } else {  
             smsForm.setFile(item);  
           }  
         }  
       } catch (Exception e) {  
         e.printStackTrace();  
       }        
     }   
   }  

No comments: