gpt4 book ai didi

java - 在不和谐机器人上上传用户文件

转载 作者:行者123 更新时间:2023-12-02 01:16:55 24 4
gpt4 key购买 nike

我试图让用户在不和谐上提交文件,然后将其上传到网站进行处理。但是,我的代码似乎有问题。

当我上传文件时,我收到响应代码 400(错误请求),但该网站应该接受 w3g 格式的文件。

private static void onFileUpload(Message.Attachment attachment, TextChannel channel) {
// api.wc3stats.com/upload
String fileName = attachment.getFileName();
if (fileName.substring(fileName.length() - 3).equals("w3g")) {

File file = new File(attachment.getFileName());
attachment.downloadToFile(file);
try {
HttpHelper.postFile(file, "https://api.wc3stats.com/upload");
channel.sendMessage("Uploading: " + file.toString()).queue();
} catch (IOException e) {
e.printStackTrace();
channel.sendMessage(e.getMessage()).queue();
}
System.out.println("Deleted");
file.delete();

} else {
channel.sendMessage("Invalid file type.").queue();
}
}

public static void postFile(File file, String url) throws IOException {
HttpURLConnection connection = null;
FileInputStream fis = null;
BufferedInputStream bis = null;
BufferedOutputStream out = null;
try {
URL urlForPostRequest = new URL(url);
connection = (HttpURLConnection) urlForPostRequest.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);


//if (responseCode == HttpURLConnection.HTTP_OK) {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
out = new BufferedOutputStream(connection.getOutputStream());
byte[] buffer = new byte[8192];
int i;
while ((i = bis.read(buffer)) > 0) {
out.write(buffer, 0, i);
}
//}
int responseCode = connection.getResponseCode();
System.out.println("Response: " + connection.getResponseMessage());
System.out.println(responseCode);
} finally {
if (fis != null) fis.close();
if (bis != null) bis.close();
if (out != null) out.close();
System.out.println("closed");
}
}

它向我抛出的当前异常是找不到该文件。但我可以在附加到discord并下载后在程序目录中清楚地看到它。这也只发生在我第一次上传文件时。我第二次上传相同的文件时,它只会给我错误的请求响应。

首次上传尝试 LastReplay.w3g 输出:

    java.io.FileNotFoundException: lol.w3g 
C:\SomePath\lol.w3g
cannot be read
closed
Deleted

我还可以注意到该文件现在存在于程序目录中。尽管一切完成后它应该被删除。

第二次上传 LastReplay.w3g 输出

C:\SomePath\lol.w3g
Can be read
Response: Bad Request
closed
Deleted

最佳答案

我设法使用 Javascript 并使用 request-promise 的帮助来做到这一点,至于 java 我没有......

        if (msg.attachments.size > 0) {
let attached = msg.attachments.array()[0];
const request = require('request-promise');
let formData = {
file: request (attached.url)
};
request.post('https://api.wc3stats.com/upload', {formData, json: true})
.then(function (json) {
// on success handle response json
})
.catch(function (err) {
console.log(err);
});
}

关于java - 在不和谐机器人上上传用户文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57655598/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com