您的位置:首页 > 编程语言 > Java开发

单个文件或图片上传(java)

2016-09-21 16:00 447 查看
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);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  上传 单个文件