You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

安卓应用向Spring服务器上传图片时遇到问题求助

解决Android上传图片到Spring服务器的问题

嘿,我看你在把Android端的图片上传到Spring服务器时遇到了问题,先从你贴的服务器代码里找核心问题哈!

你的代码里的关键错误

你用了@RequestBody来接收MultipartFile,这是不对的!因为@RequestBody是用来解析JSON格式的请求体,而文件上传的请求格式是multipart/form-data,两者完全不兼容,所以服务器根本没法正确识别你上传的文件。

修正后的服务器端代码

@RequestBody换成@RequestParam(或者@RequestPart,效果类似),同时明确指定接口接收multipart/form-data类型的请求:

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import java.nio.file.Files;
import java.nio.file.Paths;

@RequestMapping(value = "/upload", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public String fileUpload(@RequestParam("file") MultipartFile file) {
    System.out.println("post image");
    try {
        byte[] bytes = file.getBytes();
        System.out.println(bytes.length);
        // 补全你的文件保存路径,记得替换成实际存在的目录
        String savePath = "E:/together/image/" + file.getOriginalFilename();
        Files.write(Paths.get(savePath), bytes);
        return "文件上传成功";
    } catch (Exception e) {
        e.printStackTrace();
        return "文件上传失败:" + e.getMessage();
    }
}

额外注意事项

  • Spring配置检查:如果是Spring Boot项目,默认已经开启了Multipart文件上传支持;如果是传统Spring MVC,需要在配置类或xml里配置MultipartResolver,确保能处理文件上传请求。
  • Android端请求格式:上传时必须用multipart/form-data格式发送请求,比如用OkHttp的示例代码:
OkHttpClient client = new OkHttpClient();
File imageFile = new File("/sdcard/your_image.jpg");
RequestBody requestBody = new MultipartBody.Builder()
        .setType(MultipartBody.FORM)
        .addFormDataPart("file", imageFile.getName(), 
                RequestBody.create(MediaType.parse("image/jpeg"), imageFile))
        .build();

Request request = new Request.Builder()
        .url("http://你的服务器地址/upload")
        .post(requestBody)
        .build();

// 执行请求
try (Response response = client.newCall(request).execute()) {
    if (response.isSuccessful()) {
        // 处理成功响应
    }
} catch (IOException e) {
    e.printStackTrace();
}
  • 文件权限:确保Spring应用有写入E:/together/image/目录的权限,不然会抛出IO异常导致上传失败。

内容的提问来源于stack exchange,提问作者user9570040

火山引擎 最新活动