我需要有关使用 Jersey 上传多个文件的帮助。我使用以下代码使用 Jersey 上传单个文件。
package my.first.rest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
import com.sun.jersey.core.header.FormDataContentDisposition;
import com.sun.jersey.multipart.FormDataParam;
@Path("uploadfile")
public class Upload {
String location;
@POST
@Path("/upload")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public String uploadfile(@FormDataParam("file") InputStream is, @FormDataParam("file") FormDataContentDisposition filedetail){
saveToDisk(is,filedetail);
return "File Uploaded Succesfully_"+location;
}
private void saveToDisk(InputStream is1,
FormDataContentDisposition filedetail) {
// TODO Auto-generated method stub
location = "E://upload/"+filedetail.getFileName();
try{
OutputStream out = new FileOutputStream(new File(location));
int read = 0;
byte[] bytes = new byte[1024];
out = new FileOutputStream (new File(location));
while((read = is1.read(bytes)) != -1){
out.write(bytes,0,read);
}
out.flush();
out.close();
}catch (IOException e){
e.printStackTrace();
}
}
}
上面的代码适用于上传单个文件,但是当我将 multiple="multiple"属性添加到 input type = file 标签时,我能够在一次上传中选择多个项目,它会上传第一个选择的项目和最后选择的项目的名称。我不希望代码工作,因为它不是为了处理多个文件上传,但必须有办法解决它,对吧?因为,它使用一个文件和另一个文件的名称。
我查看了多个 stackoverflow 线程并在 google 上搜索了很多。如果我找到了答案,我就不会发布这个了。我不希望使用以下代码类型上传多个文件:
<input type ="file" name="file">
<input type ="file" name="file">
<input type ="file" name="file2">
我不想单独上传多个文件。我希望能够一次选择多个文件,并将所有文件上传到某个地方。我的标签是这样的:
<input type ="file" name="file" multiple="multiple">
这是完整的 HTML 代码。
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action ="http://localhost:8080/fuseframework/uploadfile/upload" method="post" enctype="multipart/form-data">
file:
<br>
<input type ="file" name="file" multiple="multiple">
<input type="submit" value="send">
</form>
</body>
</html>
这些是我用过的 jar http://i.stack.imgur.com/1tVT8.png
最佳答案
这件事对我很有效:
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
public void uploadMultiple(@FormDataParam("file") FormDataBodyPart body){
for(BodyPart part : body.getParent().getBodyParts()){
InputStream is = part.getEntityAs(InputStream.class);
ContentDisposition meta = part.getContentDisposition();
doUpload(is, meta);
}
}
关于java - 选择多个文件并使用 Jersey 上传它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25749472/