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")
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)