如何从控制台上传其他数据文件

时间:2016-05-27 08:58:33

标签: java objectoutputstream sendfile

我想将文件上传到我的网络服务器。 我的服务器实现了RESTful API。 要上传文件,我应该传递4个参数:file,file_name,project,version

我想从控制台上传这3个参数的文件。我试过这个

URL obj = new URL(MY_URL);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

con.setRequestMethod("POST");

con.setDoOutput(true);

ObjectOutputStream objectOutputStream = new ObjectOutputStream(con.getOutputStream());
ToSend send = new ToSend();
send.file = Files.readAllBytes(Paths.get("path"));
send.file_name  = "name";
send.project = "test";
send.version = "1";
objectOutputStream.writeObject(send);
objectOutputStream.flush();
objectOutputStream.close();

我发送的对象看起来像这样

class ToSend implements Serializable {
    byte[] file;

    String file_name;

    String project;

    String version;
}

我得到Exception in thread "main" java.io.IOException: Server returned HTTP response code: 400 for URL:

如果这很重要,我用Java + Spring编写的服务器及其方法有下一个签名

@RequestMapping(value = "/", method = RequestMethod.POST)
public @ResponseBody
Response<Boolean> upload(
    @RequestParam("project") String project,
    @RequestParam("version") String version,
    @RequestParam("file_name") String fileName,
    @RequestParam("file") MultipartFile file
) throws ServiceException, BadFileExtension {
    boolean success = storageService.uploadFile(file, project, fileName, version);

    return builder.get(success);
}

1 个答案:

答案 0 :(得分:0)