html页面:
<input type="file" class="inputPic" allowexts="gif,jpeg,jpg,png,bmp" accept="image/*">
js文件:
$(".inputPic").change(function() {var serviceUrl = getProjectURL();var userguid = $("#userguid").val();var url = serviceUrl + "/myinformation/uploadheadimg";var form = new FormData();var file=$(".inputPic")[0].files;form.append("myfile", new Blob(file));form.append("userguid", userguid);var xhr = new XMLHttpRequest(); xhr.open("post", url, true); // poxhr.upload.onloadstart = function() {// 上传开始执行方法ot = new Date().getTime(); // 设置上传开始时间oloaded = 0;// 设置上传开始时,以上传的文件大小为0};xhr.send(form); // 开始上传,发送form数据xhr.responseText = function(res) {console.log(res);}xhr.onreadystatechange = function(response) {console.log(response);if (response.target.readyState == '4') {var result = JSON.parse(response.target.response);if (Number(result.data) == 0) {alert(result.msg);} else {alert("封面上传成功");$("#cropperModel").modal('hide');}}}});
java后台:
@ResponseBody@RequestMapping("/uploadheadimg")public JSONObject uploadheadimg(HttpServletRequest request, HttpSession session) {try {System.out.println("开始上传头像......");String newFileName = null;String userguid = request.getParameter("userguid");System.out.println(userguid);UserInfo userinfo=userService.getUserByGuid(userguid);SysConfig config = configService.getByName("isuptoaliyun");if (ServletFileUpload.isMultipartContent(request)) {if ("0".equals(config.getConfigvalue())) {MultipartHttpServletRequest fileUpload = (MultipartHttpServletRequest) request;MultipartFile multifile = fileUpload.getFile("myfile");String filetype = multifile.getContentType();String realPath = PropertiesUtil.getValue("FILEPATH", "fileconfig.properties");if (filetype.contains("png")) {newFileName = sdf.format(new Date()) + "_"+ userguid.substring(userguid.length() - 6, userguid.length()) + ".png";} else if (filetype.contains("jpg")) {newFileName = sdf.format(new Date()) + "_"+ userguid.substring(userguid.length() - 6, userguid.length()) + ".jpg";}File targetFile = new File(realPath, newFileName);multifile.transferTo(targetFile);FileInfo fileinfo = new FileInfo();fileinfo.setAddtime(new Date());fileinfo.setFilepath(targetFile.getAbsolutePath().replace("\\", "&&"));String ipconfig = PropertiesUtil.getValue("IPCONFIG", "fileconfig.properties");fileinfo.setFileurl("http://" + ipconfig + "/upload/" + newFileName);fileinfo.setFilesize(request.getContentLength());fileinfo.setRowguid(UUID.randomUUID().toString());fileinfo.setCliengguid(UUID.randomUUID().toString());fileService.addFileInfo(fileinfo);userinfo.setLogoguid(fileinfo.getCliengguid());userinfo.setLogopicurl(fileinfo.getFileurl());userService.updateUser(userinfo);} else {String endpoint = ConfigUtil.getProperty("endpoint");String accessKeyId = ConfigUtil.getProperty("accessKeyId");String accessKeySecret = ConfigUtil.getProperty("accessKeySecret");String bucketName = ConfigUtil.getProperty("bucketName");String firstKey = "headimg/"+UUID.randomUUID().toString();OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);try {MultipartHttpServletRequest fileUpload = (MultipartHttpServletRequest) request;MultipartFile multifile = fileUpload.getFile("myfile");if (ossClient.doesBucketExist(bucketName)) {} else {ossClient.createBucket(bucketName);}InputStream is1 = new ByteArrayInputStream(multifile.getBytes());PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName,firstKey,is1);ObjectMetadata metadata = new ObjectMetadata();metadata.setObjectAcl(CannedAccessControlList.PublicRead);putObjectRequest.setMetadata(metadata);ossClient.putObject(putObjectRequest);OSSObject ob = ossClient.getObject(bucketName,firstKey);String url = ob.getResponse().getUri();FileInfo fileinfo = new FileInfo();fileinfo.setRowguid(UUID.randomUUID().toString());fileinfo.setFilesize(request.getContentLength());fileinfo.setAddtime(new Date());fileinfo.setFilepath(firstKey);fileinfo.setFileurl(url);fileinfo.setIstoali("1");fileinfo.setCliengguid(UUID.randomUUID().toString());fileService.addFileInfo(fileinfo);userinfo.setLogoguid(fileinfo.getCliengguid());userinfo.setLogopicurl(fileinfo.getFileurl());userService.updateUser(userinfo);} catch (OSSException oe) {oe.printStackTrace();} catch (ClientException ce) {ce.printStackTrace();} catch (Exception e) {e.printStackTrace();} finally {ossClient.shutdown();}}}return BuildJsonOfObject.getSuccessJSONString(MSG.SUCCESSCODE,MSG.SystemSuccess);} catch (Exception e) {e.printStackTrace();return BuildJsonOfObject.getErrorJSONString(MSG.SUCCESSCODE,e.getMessage());}}
希望对你有所帮助
如果觉得《js 获取input type=file 文件 并且上传》对你有帮助,请点赞、收藏,并留下你的观点哦!