1. 程式人生 > >java實現檔案上傳的簡單demo

java實現檔案上傳的簡單demo

在實際開發中,經常會遇到上傳檔案到伺服器的操作,因此在這裡就舉一個簡單的例子

public class PathUtils {

    public static String getFolderPath(){
        String path = System.getProperty("user.dir");
        File file = new File(path);
        File parentFile = file.getParentFile();
        path = parentFile.getPath() + "/" + "xcFile";
        return
path; } }
public Result<?> uploadFile(MultipartFile multipartFile, HttpServletRequest request) throws ParserConfigurationException, TransformerException, IOException {
        if(multipartFile == null){
            return Result.newFaild("檔案資訊不完整!");
        }
        //獲取工程上傳資料夾相對路徑
        String path = PathUtils.getFolderPath
(); String contextPath = path + "/" + fileType; if(!multipartFile.isEmpty()){ String fileName = multipartFile.getOriginalFilename(); try { File tempFile = new File(contextPath); if (!tempFile.exists()) { tempFile.mkdirs
(); } String[] strs = fileName.split("\\."); if (strs.length < 2) { return Result.newFaild("檔案沒有副檔名"); } String extensionName = "." + strs[strs.length - 1]; contextPath += "/" +StringUtil.toHexString(fileName.replace(extensionName, "")) + extensionName; BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream( new File(contextPath))); out.write(multipartFile.getBytes()); out.flush(); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); return Result.newFaild("上傳失敗," + e.getMessage()); } catch (IOException e) { e.printStackTrace(); return Result.newFaild("上傳失敗," + e.getMessage()); } }else { return Result.newFaild("檔案不可為空!"); } return Result.newSuccess("上傳成功!"); }