标签:
先导入 cos-26Dec2008.jar包
package com.lxinet.qqorder.controller; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.List; import com.jfinal.core.Controller; import com.jfinal.kit.PathKit; import com.jfinal.upload.UploadFile; /** * 上传文件 * @author cz */ public class UploadController extends Controller { public void doUpload() { String path = new SimpleDateFormat("yyyyMMdd").format(new Date()); UploadFile file = getFile("filedata", PathKit.getWebRootPath() + "/temp"); File source = file.getFile(); String fileName = file.getFileName(); String extension = fileName.substring(fileName.lastIndexOf(".")); String prefix = "upload/"; try { if (".png".equals(extension) || ".jpg".equals(extension) || ".gif".equals(extension)) { prefix += "img"; fileName = generateWord() + extension; } else { prefix += "file"; } FileInputStream fis; fis = new FileInputStream(source); File targetDir = new File(PathKit.getWebRootPath() + "/" + prefix + "/" + path); if (!targetDir.exists()) { targetDir.mkdirs(); } File target = new File(targetDir, fileName); if (!target.exists()) { target.createNewFile(); } FileOutputStream fos = new FileOutputStream(target); byte[] bts = new byte[300]; while (fis.read(bts, 0, 300) != -1) { fos.write(bts, 0, 300); } fos.close(); fis.close(); setAttr("statusCode", 200); setAttr("message", ""); setAttr("filename", "" + prefix + "/" + path + "/" + fileName); source.delete(); } catch (Exception e) { e.printStackTrace(); } renderJson(); } private String generateWord() { String[] beforeShuffle = new String[] { "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" }; List<String> list = Arrays.asList(beforeShuffle); Collections.shuffle(list); StringBuilder sb = new StringBuilder(); for (int i = 0; i < list.size(); i++) { sb.append(list.get(i)); } String afterShuffle = sb.toString(); String result = afterShuffle.substring(5, 9); return result; } }
标签:
原文地址:http://my.oschina.net/zchuanzhao/blog/518842