标签:单个文件(或图片)上传
public void uploadFile(){
UploadFile file = getFile("batfile", "images");
File source = file.getFile();
String fileName = file.getFileName();
String extension = fileName.substring(fileName.lastIndexOf("."));
String prefix;
if(".png".equals(extension) || ".jpg".equals(extension) || ".gif".equals(extension)){
prefix = "images";
fileName = WebUtils.uuid() + extension;
}else{
prefix = "files";
}
JSONObject json = new JSONObject();
try {
FileInputStream fis = new FileInputStream(source);
File targetDir = new File(PropKit.use("config.properties").get("file.path") + prefix + "/");
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();
json.put("error", "success");
json.put("url", prefix + "/"+ fileName);
source.delete();
} catch (FileNotFoundException e) {
json.put("error", 1);
json.put("message", "上传出现错误,请稍后再上传");
} catch (IOException e) {
json.put("error", 1);
json.put("message", "文件写入服务器出现错误,请稍后再上传");
}
renderJson(PropKit.use("config.properties").get("file.path") + "files/"+ fileName);
}
本文出自 “不凡人生——求知者” 博客,谢绝转载!
标签:单个文件(或图片)上传
原文地址:http://825272560.blog.51cto.com/11004487/1855007