怎么用java程序实现上传文件到指定的URL地址

2025-03-21 21:58:26
推荐回答(1个)
回答1:

//保存图片
private void saveImg(HttpServletRequest request,FormFile imgFile,FileForm fileForm){
if (imgFile != null && imgFile.getFileSize() > 0) {
    String fileName = imgFile.getFileName();
    String sqlPath = "img/" + fileName;
    //图片所在路径
    String savePath = request.getSession().getServletContext().getRealPath("/")+ "img\\" + fileName;
    System.out.println(fileName);
    System.out.println(sqlPath);
    System.out.println(savePath);
    HttpSession session=request.getSession();
    session.setAttribute("savePath", savePath);
    session.setMaxInactiveInterval(60*60);
    //String savePath1=(String)session.getAttribute("savePath");
    // 数据库
    fileForm.getFile().setFileEmpPhoto(sqlPath);
    // 文件
    try {
        InputStream input = imgFile.getInputStream();
        FileOutputStream output = new FileOutputStream(savePath);
        byte[] b = new byte[1024];
        while (input.read(b) != -1) {
            output.write(b);
            b = new byte[1024];
        }
        output.close();
        input.close();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
}