java实现多文件上传

java实现多文件上传,第1张

即使再多文件也是通过的单个文件逐次上传的(zip等压缩包实际上是盯者一个文件)。实现思路就是将多个文件循环进行上传,上传方法举例:

/**

* 上传文件

*

* @param fileName

* @param plainFilePath 文件路径路径

* @param filepath

* @return

* @throws Exception

*/

public static String fileUploadByFtp(String plainFilePath, String fileName, String filepath) throws Exception {

FileInputStream fis = null

ByteArrayOutputStream bos = null

FTPClient ftpClient = new FTPClient()

String bl = "false"

try {

fis = new FileInputStream(plainFilePath)

bos = new ByteArrayOutputStream(fis.available())

byte[] buffer = new byte[1024]

int count = 0

while ((count = fis.read(buffer)) != -1) {

bos.write(buffer, 0, count)

}

bos.flush()

Log.info("加密上传文件开始")

Log.info("连接远程上传服务器"+CCFCCBUtil.CCFCCBHOSTNAME+":"+22)

ftpClient.connect(CCFCCBUtil.CCFCCBHOSTNAME, 22)

ftpClient.login(CCFCCBUtil.CCFCCBLOGINNAME, CCFCCBUtil.CCFCCBLOGINPASSWORD)

FTPFile[] fs

fs = ftpClient.listFiles()

for (FTPFile ff : fs) {

if (ff.getName().equals(filepath)) {

bl="true"

ftpClient.changeWorkingDirectory("/"+filepath+"")

}

}

Log.info("检查文件路径是否存在:/"谨答+filepath)

if("false".equals(bl)){

ViewUtil.dataSEErrorPerformedCommon( "查询文件路径不存在:"+"/"+filepath)

return bl

}

ftpClient.setBufferSize(1024)

ftpClient.setControlEncoding("GBK")

// 设置文件类型(二进制)

ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE)

ftpClient.storeFile(fileName, fis)

Log.info("上传文件成功:"+fileName+"。祥则慧文件保存路径:"+"/"+filepath+"/")

return bl

} catch (Exception e) {

throw e

} finally {

if (fis != null) {

try {

fis.close()

} catch (Exception e) {

Log.info(e.getLocalizedMessage(), e)

}

}

if (bos != null) {

try {

bos.close()

} catch (Exception e) {

Log.info(e.getLocalizedMessage(), e)

}

}

}

}

备注:只需要修改上传的服务器地址、用户名、密码即可进行服务器访问上传。根据实际需要修改即可。

java中是可以支持多文件上传的,参考代码如下:

@RequestMapping(value = {"multipleFileUpload"}, method =  {RequestMethod.GET, RequestMethod.POST})

    public  String multipleFileUpload(

            ModelMap modelMap,

            MultipartHttpServletRequest request,

            HttpServletResponse response,

            @RequestParam(value = "type") String type,

            @RequestParam(value = "jobId") String jobId) throws IOException {

        List < MultipartFile > files = request.getFiles("files")

        response.setHeader("Access-Control-Allow-Origin", "http://www.gifmiao.com")

        Map<String, Object> statusMap = new HashMap<>()

        HttpSession session = request.getSession()

        session.setAttribute("gifCompressStatus", statusMap)

        int compressSize = getCompressSizeByValue(type)

        for(MultipartFile file :files){

   搭高         String filename = file.getOriginalFilename().split(".gif")[0]

            Map<String, Object> resultMap = new HashMap<>()

            resultMap.put("size" , 0)

            resultMap.put("status" , 0)

  昌悔          resultMap.put("url" , "")

            statusMap.put(filename, resultMap)

            InputStream is = file.getInputStream()

            byte[] bytes = IOUtils.toByteArray(is)

            CompressWorker worker = new CompressWorker(statusMap, bytes, filename, compressSize, jobId)

            worker.start()

        }

        modelMap.addAttribute("json", StringUtils.toInsensitiveJson(new ReturnMap("线程已启动")))

     耐枝正   return "json"

    }

//1.form表单

//注:上传文件的表单,需要将form标签设置enctype="multipart/form-data"属性,意思是将Content-Type设置成multipart/form-data

<form action="xxx" method="post" enctype="multipart/form-data">

<input type="text" name="name" id="id1" /><br />

<input type="password" name="禅毕password" /> <br />

<input type="file" name="file" value="选择文件"/><input id="submit_form"庆扒 type="submit" value="提交"/>

</form>

//2.servlet实现文件接收的功能

boolean isMultipart = ServletFileUpload.isMultipartContent(request)//判断是否是表单文件类型

DiskFileItemFactory factory = new DiskFileItemFactory()

ServletFileUpload sfu = new ServletFileUpload(factory)

List items = sfu.parseRequest(request)//从request得到所有上传域的列表

for(Iterator iter = items.iterator()iter.hasNext()){

FileItem fileitem =(FileItem) iter.next() if(!fileitem.isFormField()&&fileitem!=null){

//判读不是普通表单域即是file

System.out.println("name:"+fileitem.getName())

}

}

3.扩展一下springboot

@RequestMapping("/xxx")

@ResponseBody

public String handleFileUpload(@RequestParam("file"誉袭昌) MultipartFile file) {

if (!file.isEmpty()) {

try {

BufferedOutputStream out = new BufferedOutputStream(

new FileOutputStream(new File(

file.getOriginalFilename())))

System.out.println(file.getName())

out.write(file.getBytes())

out.flush()

out.close()

} catch (FileNotFoundException e) {

e.printStackTrace()

return "上传失败," + e.getMessage()

} catch (IOException e) {

e.printStackTrace()

return "上传失败," + e.getMessage()

}

return "上传成功"

} else {

return "上传失败,因为文件是空的."

}

}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/tougao/12293972.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-24
下一篇 2023-05-24

发表评论

登录后才能评论

评论列表(0条)

保存