java rest 文件上传_java – 使用REST上传多个文件

我的html中有一个input type = file标签,允许用户选择多个文件.表单的操作是REST Web服务:

@POST

@Path("savefile")

@Produces ({MediaType.TEXT_PLAIN})

public String createObjects(

@FormDataParam("datafile") FormDataMultiPart file,

@FormParam("username") String unm

//@Context HttpServletRequest request

){....}

最初,我使用请求对象检索请求中的所有FileItem,然后将其保存到服务器.没问题.现在我想发送一个字符串数据和文件.为此,我读到参数需要是FormDataParam类型.因此我添加了该参数.这是我的客户端代码:

enctype="multipart/form-data" method="post">

type="file" name="datafile" required="required" autofocus="autofocus"

οnchange="selectFiles(this)"/>

我不确定什么必须是文件参数的类型,以允许其中的多个文件????

文件参数给我多个文件还是我必须恢复到@Context注入?如果是这样,我将如何检索字符串参数?

欢迎任何帮助!

编辑:

我已将我的REST修改为以下内容:

@POST

@Path("savefile")

//@Consumes (MediaType.MULTIPART_FORM_DATA)

public void createObjects(

//@FormDataParam("datafile") FormDataMultiPart file,

//@FormParam("username") String unm

@Context HttpServletRequest request

)

{

try

{

FileHandler f;

f = new FileHandler(new File (getClass().getResource("/" +getClass().getName().substring(

0, getClass().getName().indexOf("."))).getPath()).getParent().replaceAll("\\", "\\\\") + "/mylog.log");

logger.addHandler(f);

}

catch (SecurityException e1)

{

logger.info(e1.getMessage());

}

catch (IOException e1)

{

logger.info(e1.getMessage());

//e1.printStackTrace();

}

ApplicationConstants.ROOTPATH = new File (getClass().getResource("/" +getClass().getName().substring(

0, getClass().getName().indexOf("."))).getPath()).getParent().replaceAll("\\", "\\\\") ;

ApplicationConstants.ROOTPATH = ApplicationConstants.ROOTPATH.substring

(0, ApplicationConstants.ROOTPATH.indexOf("\") + 2);

String user = request.getParameter("username");

logger.info("ApplicationConstants.ROOTPATH" + ApplicationConstants.ROOTPATH);

try

{

for (Part part : request.getParts())

{

try

{

logger.info("part = " + part.getName());

if (!part.getName().equalsIgnoreCase("username"))

{

String fileName = processFileName(part.getName());

part.write(new File(ApplicationConstants.ROOTPATH + user + "\" + fileName).getPath());

}

else

{

user = request.getParameter("username");

logger.info("user = " + user);

}

}

catch (IOException e)

{

logger.info(e.getMessage());

}

}

}

catch (IOException e)

{

}

catch (ServletException e)

{

}

}

但我总是从request.getParameter(“username”)获取值为null.我不知道出了什么问题!!以多部分/表格数据形式发送其他数据是否违法?我需要一些指示.请在此代码中提出任何改进建议.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值