【发布时间】:2018-04-18 11:28:44
【问题描述】:
我正在尝试使用 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 调用,它将为休息服务提供这两个参数
【问题讨论】:
标签: javascript java jersey-2.0