1. String targetUrl = "http://localhost:8080/Test";
2. new PostMethod(targetUrl) {//这个用来中文乱码
3. public String getRequestCharSet() {
4. return "UTF-8";//
5. }
6. };
7. try {
8. new HttpClient();
9. new File("c:/新闻.xml");
10. new Part[] {new CustomFilePart(file.getName(), file)};
11. new MultipartRequestEntity(parts, filePost.getParams()));
12. int statuscode=client.executeMethod(filePost);
13. if(statuscode == HttpStatus.SC_OK) {
14. System.out.println("添加文件成功");
15. } else {
16. System.out.println("添加文件失败");
17. }
18. } catch (Exception ex) {
19. ex.printStackTrace();
20. }
1. import java.io.File;
2. import java.io.FileNotFoundException;
3. import java.io.IOException;
4. import java.io.OutputStream;
5.
6. import org.apache.commons.httpclient.methods.multipart.FilePart;
7. import org.apache.commons.httpclient.util.EncodingUtil;
8. /**
9. *解决中文文件名乱码
10. */
11. public class CustomFilePart extends FilePart {
12. public CustomFilePart(String filename, File file)
13. throws FileNotFoundException {
14. super(filename, file);
15. }
16.
17. protected void sendDispositionHeader(OutputStream out) throws IOException {
18. super.sendDispositionHeader(out);
19. String filename = getSource().getFileName();
20. if (filename != null) {
21. out.write(EncodingUtil.getAsciiBytes(FILE_NAME));
22. out.write(QUOTE_BYTES);
23. "utf-8"));
24. out.write(QUOTE_BYTES);
25. }
26. }
27. }
而服务端使用apache的commonfileupload:
1. File tempfile = new File(System.getProperty("java.io.tmpdir")); // 采用系统临时文件目录
2. new DiskFileItemFactory();
3. 4096); // 设置缓冲区大小,这里是4kb
4. // 设置缓冲区目录
5. new ServletFileUpload(diskFileItemFactory);
6. 4194304); // 限制文件大小最大为4M
7. List fileItems = fu.parseRequest(request);
8. Iterator i = fileItems.iterator();
9. while (i.hasNext()) {
10. FileItem fi = (FileItem) i.next();
11. String fileName = fi.getName();
12. if (fileName != null) {
13. new File(fi.getName());
14. new File(uploadPath, fullFile.getName());
15. fi.write(savedFile);
16. }
17. }
18. "upload succeed");