apache 如何http上传文件
2个回答
展开全部
JAVA代码
String targetUrl = "http://localhost:8080/Test";
PostMethod filePost = new PostMethod(targetUrl) {//这个用来中文乱码
public String getRequestCharSet() {
return "UTF-8";//
}
};
try {
HttpClient client = new HttpClient();
File file = new File("c:/新闻.xml");
Part[] parts = new Part[] {new CustomFilePart(file.getName(), file)};
filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
int statuscode=client.executeMethod(filePost);
if(statuscode == HttpStatus.SC_OK) {
System.out.println("添加文件成功");
} else {
System.out.println("添加文件失败");
}
} catch (Exception ex) {
ex.printStackTrace();
}
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.util.EncodingUtil;
/**
*解决中文文件名乱码
*/
public class CustomFilePart extends FilePart {
public CustomFilePart(String filename, File file)
throws FileNotFoundException {
super(filename, file);
}
protected void sendDispositionHeader(OutputStream out) throws IOException {
super.sendDispositionHeader(out);
String filename = getSource().getFileName();
if (filename != null) {
out.write(EncodingUtil.getAsciiBytes(FILE_NAME));
out.write(QUOTE_BYTES);
out.write(EncodingUtil.getBytes(filename, "utf-8"));
out.write(QUOTE_BYTES);
}
}
}
而服务端使用apache的commonfileupload:
File tempfile = new File(System.getProperty("java.io.tmpdir")); // 采用系统临时文件目录
DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
diskFileItemFactory.setSizeThreshold(4096); // 设置缓冲区大小,这里是4kb
diskFileItemFactory.setRepository(tempfile); // 设置缓冲区目录
ServletFileUpload fu = new ServletFileUpload(diskFileItemFactory);
fu.setSizeMax(4194304); // 限制文件大小最大为4M
List fileItems = fu.parseRequest(request);
Iterator i = fileItems.iterator();
while (i.hasNext()) {
FileItem fi = (FileItem) i.next();
String fileName = fi.getName();
if (fileName != null) {
File fullFile = new File(fi.getName());
File savedFile = new File(uploadPath, fullFile.getName());
fi.write(savedFile);
}
}
System.out.println("upload succeed");
2014-05-11
展开全部
有ftp服务吗
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询
广告 您可能关注的内容 |