java图片写入指定目录_java 上传图片到本地指定路径(并按年月日文件夹分类保存)实例...

工具类方法

PhotoUtils里的方法

//上传图片

public static String uploadFile(HttpServletRequest request, MultipartFile uploadFile) throws IOException {

SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSS");

String res = sdf.format(new Date());

//设置的保存路径

String rootPath ="E://upload/";

//原始名称

String originalFilename = uploadFile.getOriginalFilename();

//生成文件名

String newFileName = res + UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));

//创建年月日文件夹

Calendar date = Calendar.getInstance();

File dateDirs = new File(date.get(Calendar.YEAR)

+ File.separator + (date.get(Calendar.MONTH) + 1) + File.separator + (date.get(Calendar.DATE)));

//新文件

File newFile = new File(rootPath + Fil

  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用Java中的URLConnection类来实现文件上传。下面是一个简单的示例代码: ``` import java.io.File; import java.io.FileInputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; public class FileUploader { public static void main(String[] args) { String serverUrl = "http://example.com/upload.php"; // 服务器上传接口地址 String filePath = "path/to/image.jpg"; // 本地文件路径 String serverPath = "/var/www/html/uploads/"; // 服务器目标路径 try { // 创建连接 URL url = new URL(serverUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=---------------------------123821742118716"); connection.setRequestProperty("Content-Disposition", "form-data; name=\"file\"; filename=\"" + new File(filePath).getName() + "\""); // 读取文件并写入请求体 FileInputStream fileInputStream = new FileInputStream(new File(filePath)); OutputStream outputStream = connection.getOutputStream(); byte[] buffer = new byte[4096]; int bytesRead = -1; while ((bytesRead = fileInputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } // 结束请求体 outputStream.flush(); outputStream.write("\r\n".getBytes()); outputStream.write("-----------------------------123821742118716--\r\n".getBytes()); // 发送请求并获取响应 int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { System.out.println("文件上传成功!"); } else { System.out.println("文件上传失败,错误代码:" + responseCode); } // 关闭连接 fileInputStream.close(); outputStream.close(); connection.disconnect(); } catch (Exception e) { e.printStackTrace(); } } } ``` 在上面的代码中,我们创建一个HTTP连接对象,并设置请求头部信息。然后,我们读取本地文件,将其写入请求体,再发送请求并获取响应。最后,我们关闭连接。请注意,这段代码只是一个示例,你需要根据自己的实际情况进行修改。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值