上传文件

来源:互联网 发布:网络课程运营 编辑:程序博客网 时间:2024/05/01 23:15

public JSONObject saveFile(String fileName, String userId) {  System.out.println("文件名是:" + fileName);  // 异步上传时,无法通过File source = uploadFile.getFile();获取文件  File source = new File(PathKit.getWebRootPath() + "/upload/" + fileName); // 获取临时文件对象  String savePath = "";  // 有userId传入说明是修改用户的文件,否则是添加用户文件  savePath = PathKit.getWebRootPath() + "/doc/" + userId;  JSONObject json = new JSONObject();  try {    FileInputStream fis = new FileInputStream(source);    File targetDir = new File(savePath);    if (!targetDir.exists()) {      targetDir.mkdirs();    }    File target = new File(targetDir, fileName);    int i = 1;    while (target.exists()) {// 防止覆盖同名文件      i++;      target = new File(targetDir, "副本" + i + fileName);    }    target.createNewFile();    System.out.println(PathKit.getWebRootPath());    FileOutputStream fos = new FileOutputStream(target);    byte[] bts = new byte[1024 * 20];    while (fis.read(bts, 0, 1024 * 20) != -1) {       fos.write(bts, 0, 1024 * 20);    }    fos.close();    fis.close();    json.put("error", 0);    // 相对地址,显示图片用   json.put("file_path", "/cp_platform/doc/" + userId + "/" + fileName);   json.put("file_name", fileName);   json.put("message", "上传成功");   source.delete();   } catch (FileNotFoundException e) {     e.printStackTrace();     json.put("error", 1);     json.put("message", "上传出现错误,请稍后再上传");   } catch (IOException e) {     e.printStackTrace();     json.put("error", 1);     json.put("message", "文件写入服务器出现错误,请稍后再上传");   }     return json;}


0 0