Subversion Repositories SmartDukaan

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
5531 mandeep.dh 1
/**
2
 * 
3
 */
4
package in.shop2020.util;
5
 
6
import java.io.File;
7
import java.io.FileFilter;
8
import java.io.IOException;
9
import java.io.UnsupportedEncodingException;
10
import java.util.ArrayList;
11
import java.util.Arrays;
12
import java.util.List;
13
 
14
import org.apache.http.HttpResponse;
15
import org.apache.http.client.ClientProtocolException;
16
import org.apache.http.client.HttpClient;
17
import org.apache.http.client.methods.HttpPost;
18
import org.apache.http.entity.mime.MultipartEntity;
19
import org.apache.http.entity.mime.content.FileBody;
20
import org.apache.http.entity.mime.content.StringBody;
21
import org.apache.http.impl.client.DefaultHttpClient;
22
 
23
/**
24
 * @author mandeep
25
 * 
26
 */
27
public class FileUploader {
28
    private static String url = "http://localhost:8080/Support/file-archive";
29
 
30
    public static void main(String[] args) throws IOException {
31
        Integer fileType = 1;
32
        String pathToFile = "/home/mandeep/Desktop";
33
 
34
        if (args != null && args.length == 2) {
35
            fileType = Integer.parseInt(args[0]);
36
            pathToFile = args[1];
37
        }
38
 
39
        List<File> filesToBeUploaded = new ArrayList<File>();
40
        File file = new File(pathToFile);
41
        if (file.isDirectory()) {
42
            filesToBeUploaded.addAll(Arrays.asList(file.listFiles(new FileFilter() {
43
                /* (non-Javadoc)
44
                 * @see java.io.FileFilter#accept(java.io.File)
45
                 */
46
                public boolean accept(File file) {
47
                    return file.isFile();
48
                }
49
            })));
50
        }
51
        else {
52
            filesToBeUploaded.add(file);
53
        }
54
 
55
        for (File f : filesToBeUploaded) {
56
            uploadFile(fileType, f);
57
        }
58
    }
59
 
60
    private static void uploadFile(Integer fileType, File f)
61
            throws UnsupportedEncodingException, IOException,
62
            ClientProtocolException {
63
        HttpClient client = new DefaultHttpClient();
64
        HttpPost post = new HttpPost(url);
65
 
66
        MultipartEntity entity = new MultipartEntity();
67
        entity.addPart("fileType", new StringBody(fileType.toString()));
68
        entity.addPart("file", new FileBody(f));
69
        post.setEntity(entity);
70
 
71
        System.out.println("Uploading " + f.getAbsolutePath());
72
        HttpResponse response = client.execute(post);
73
        System.out.println(response.getStatusLine());
74
        byte[] b = new byte[1000];
75
        response.getEntity().getContent().read(b);
76
        System.out.println(new String(b));
77
    }
78
}