java上传图片到服务器,并返回可访问图片的url地址
在Java中,你可以使用HttpURLConnection
或者第三方库如Apache HttpClient来上传图片到服务器,并返回可访问图片的URL地址。以下是使用HttpURLConnection
的一个简单示例:
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
public class ImageUploader {
public static void uploadImage(String targetUrl, File imageFile) throws IOException {
String boundary = Long.toHexString(System.currentTimeMillis()); // 随机边界
String CRLF = "\r\n"; // 换行符
String charset = "UTF-8"; // 设置编码
URL url = new URL(targetUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
try (
OutputStream output = connection.getOutputStream();
PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, charset), true);
) {
// 发送文件数据
writer.append("--" + boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name=\"image\"; filename=\"" + imageFile.getName() + "\"").append(CRLF);
writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(imageFile.getName())).append(CRLF);
writer.append(CRLF).flush();
Files.copy(imageFile.toPath(), output);
output.flush(); // 确保图片数据被发送
writer.append(CRLF).flush(); // 结束标记
} catch (Exception e) {
e.printStackTrace();
}
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
// 打印服务器回传的可访问图片URL地址
System.out.println(response.toS
评论已关闭