Subversion Repositories SmartDukaan

Rev

Blame | Last modification | View Log | RSS feed

/**
 * 
 */
package in.shop2020.util;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

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;

/**
 * @author mandeep
 * 
 */
public class FileUploader {
    private static String url = "http://localhost:8080/Support/file-archive";

    public static void main(String[] args) throws IOException {
        Integer fileType = 1;
        String pathToFile = "/home/mandeep/Desktop";

        if (args != null && args.length == 2) {
            fileType = Integer.parseInt(args[0]);
            pathToFile = args[1];
        }

        List<File> filesToBeUploaded = new ArrayList<File>();
        File file = new File(pathToFile);
        if (file.isDirectory()) {
            filesToBeUploaded.addAll(Arrays.asList(file.listFiles(new FileFilter() {
                /* (non-Javadoc)
                 * @see java.io.FileFilter#accept(java.io.File)
                 */
                public boolean accept(File file) {
                    return file.isFile();
                }
            })));
        }
        else {
            filesToBeUploaded.add(file);
        }

        for (File f : filesToBeUploaded) {
            uploadFile(fileType, f);
        }
    }

    private static void uploadFile(Integer fileType, File f)
            throws UnsupportedEncodingException, IOException,
            ClientProtocolException {
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(url);

        MultipartEntity entity = new MultipartEntity();
        entity.addPart("fileType", new StringBody(fileType.toString()));
        entity.addPart("file", new FileBody(f));
        post.setEntity(entity);

        System.out.println("Uploading " + f.getAbsolutePath());
        HttpResponse response = client.execute(post);
        System.out.println(response.getStatusLine());
        byte[] b = new byte[1000];
        response.getEntity().getContent().read(b);
        System.out.println(new String(b));
    }
}