gpt4 book ai didi

javascript 输入类型文件 onchange 在 java jersey Rest 上上传文件

转载 作者:行者123 更新时间:2023-12-02 11:21:19 26 4
gpt4 key购买 nike

我正在尝试使用 Java jersey REST api 在其 onchange 方法上上传文件。

下面是输入类型:

<input type="file" onchange="uploadFile($event)"/>

我得到的文件为

function uploadFile($event){
console.log($event.files[0].name)
}

下面是我的其余上传服务

@Path("/file")

public class FileUpload {
public static final String UPLOAD_FILE_SERVER = "C://Users//Feroz//Documents//filefolder//";


@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Path("/upload")
public Response getMsg( @FormDataParam("file") InputStream fileInputStream,
@FormDataParam("file") FormDataContentDisposition fileFormDataContentDisposition) {
System.out.println("ss");
String fileName = null;
String uploadFilePath = null;
try {
fileName = fileFormDataContentDisposition.getFileName();
System.out.println(fileName);

uploadFilePath = writeToFileServer(fileInputStream, fileName);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

JsonObject json = new JsonObject();
json.put("success", true);
json.put("status", "success");

json.put("path","http://localhost:8080/rest/files/download/Book1.xlsx");

return Response.status(200).entity(json).header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Headers", "accept, Cache-Control, content-type, x-requested-with")
.header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT,OPTIONS").allow("OPTIONS").build();

}

private String writeToFileServer(InputStream inputStream, String fileName) throws IOException {

OutputStream outputStream = null;
String qualifiedUploadFilePath = UPLOAD_FILE_SERVER + fileName;

try {
outputStream = new FileOutputStream(new File(qualifiedUploadFilePath));
int read = 0;
byte[] bytes = new byte[1024];
while ((read = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
outputStream.flush();
}
catch (IOException ioe) {
ioe.printStackTrace();
}
finally{
//release resource, if any
outputStream.close();
}
return qualifiedUploadFilePath;
}
}

如何通过此 onchange 方法发送 FormDataParam 和 FormDataContentDisposition 文件?我不知道如何进行 ajax 调用,它将为休息服务提供这两个参数

最佳答案

在html表单中,您需要id和enctyple

<form id="frm-file" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<button type="button" onclick="uploadFile()" />
</form>

在js中,需要jquery.form.js

function uploadFile(){
$.ajaxForm({
"formId": "frm-file",
"method": "POST",
"actionURL": context_path + "upload",
"successFun": function (data) {

}
});
}

在java中,requestParam是表单中输入的name值

@POST
@Path("/upload")
public Response getMsg(@RequestParam("file") MultipartFile multipartFile) {

}

关于javascript 输入类型文件 onchange 在 java jersey Rest 上上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49898595/

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