[英]Uploading a user file on discord bot
我试图让用户提交不一致的文件,然后将其上传到站点进行处理。 但是,我的代码似乎有问题。
当我上传文件时,我得到的响应代码为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在请求承诺的帮助下做到了这一点,因为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);
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.