« | August 2025 | » | 日 | 一 | 二 | 三 | 四 | 五 | 六 | | | | | | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | | | | | | | |
| 公告 |
戒除浮躁,读好书,交益友 |
Blog信息 |
blog名称:邢红瑞的blog 日志总数:523 评论数量:1142 留言数量:0 访问次数:9691978 建立时间:2004年12月20日 |

| |
[j2ee]解决spring中文件上传的问题 原创空间, 软件技术
邢红瑞 发表于 2005/9/13 19:19:50 |
唉,又要加班,这种加班没有加班费,不计入倒休,连晚餐补助都没有.主要是解决spring上传文件的问题,因为使用了apache的commons fileupload包,以前用的时候就发现这个问题,他没有文件重名的处理(no FileRenamePolicy),所以不得不使用cos.
spring使用cos包后问题接踵而至,先是ClassCastException,这个好解决,以后又是Corrupt form data: premature ending,终于不知道如何解决了,google半天,没有找到一个可用的例子.只好问ben alex这位高手,ben也发现这个问题,so you are uploading two files with the same name?or do you mean on the server-side, if someone uploads a file which is the same name as an existing file on the server?but it's easy o write something that will work for you, it'd only take a few lines of code.虽然代码没有几行,但是如何也改不对.ben 是个smart的人,i would personally just spend 5 minutes and write the necessary code to generate a unique server-side filename, rather than get COS to work (ie use Commons File Upload instead),还是自己写代码吧 private boolean createNewFile(File f) { try { return f.createNewFile(); } catch (IOException ignored) { return false; } }
String uploadDir = getServletContext().getRealPath("/upload/");
File dirPath = new File(uploadDir); if (!dirPath.exists()) { dirPath.mkdirs(); }
String sep = System.getProperty("file.separator"); File uploadedFile = new File(uploadDir + sep + file.getOriginalFilename()); String name=uploadedFile.getName();
String body = null; String ext = null;
int dot = name.lastIndexOf("."); if (dot != -1) { body = name.substring(0, dot); ext = name.substring(dot); // includes "." } else { body = name; ext = ""; }
int count = 1; while (!createNewFile(uploadedFile) && count < 9999) { count++; String c = new Integer(count).toString(); StringBuffer ct = new StringBuffer(c); ct.insert(0,"000"); String newName = body + ct + ext; uploadedFile = new File(uploadedFile.getParent(), newName); }
FileCopyUtils.copy(bytes, uploadedFile);
String url = "/upload/" + uploadedFile.getName();
我就不信,谁上传1万个同名文件. |
|
回复:解决spring中文件上传的问题 原创空间, 软件技术
cayu(游客)发表评论于2007/2/9 10:07:04 |
FileRenamePolicy policy = new DefaultFileRenamePolicy();
MultipartRequest multi = new MultipartRequest(request, saveDirectory, maxPostSize,policy); |
|
回复:解决spring中文件上传的问题 原创空间, 软件技术
webdev发表评论于2005/9/20 12:20:54 |
我一般是把文件名字自己改了,比如使用时间加个什么东东做文件名,这样可以避免重名问题 |
|
» 1 »
|